I have an array like this :
array(3) {
["FL_1"] => array(3) {
["MIC_1"] => array(1) {
["SP_4"] => float(7)
}
["MIC_13"] => array(1) {
["SP_16"] => float(4)
}
["MIC_6"] => array(1) {
["SP_74"] => float(4)
}
}
["FL_2"] => array(2) {
["MIC_1"] => array(1) {
["SP_5"] => float(4)
}
["MIC_13"] => array(1) {
["SP_17"] => float(4)
}
["MIC_6"] > array(1) {
["SP_75"] => float(4)
}
}
["FL_3"] => array(2) {
["MIC_1"] => array(1) {
["SP_5"] => float(89)
}
["MIC_13"] => array(1) {
["SP_18"] => float(1)
}
["MIC_6"] > array(1) {
["SP_78"] => float(21)
}
}
}
For each FL_X, I need to keep only one MIC_X that follow the conditions below :
1- This MIC_X needs to be the same for each FL_X
2- This MIC_X needs to have the lowest possible SP_Xvalue
From this example I need to get the following array
array(3) {
["FL_1"] => array(1) {
["MIC_13"] => array(1) {
["SP_16"] => float(4)
}
}
["FL_2"] => array(1) {
["MIC_13"] => array(1) {
["SP_17"] => float(6)
}
}
["FL_3"] => array(1) {
["MIC_13"] => array(1) {
["SP_18"] => float(1)
}
}
}
Any help on how to do this would be much appreciated.
Thank you !
Here's one possible solution. It uses array_walk_recursive to find the SP_X key associated with the minimum SP_X value, then it traverses the array to find the MIC_X key associated with that SP_X key and value, and finally it uses array_map and array_filter to extract only those MIC_X key values from the original array:
// find the minimum SP_X value and its key
$min_sp = PHP_INT_MAX;
$min_key = '';
array_walk_recursive($array, function ($v, $k) use (&$min_sp, &$min_key) {
if ($v < $min_sp) {
$min_sp = $v;
$min_key = $k;
}
});
// find the MIC_X key corresponding to the min SP_X value
$mic_key = '';
foreach ($array as $fl) {
foreach ($fl as $mic => $sp) {
if (isset($sp[$min_key]) && $sp[$min_key] == $min_sp) {
$mic_key = $mic;
break 2;
}
}
}
// filter the array to get all the MIC_X values
$out = array_map(function ($fl) use ($mic_key) {
return array_filter($fl, function ($mic) use ($mic_key) {
return $mic == $mic_key;
}, ARRAY_FILTER_USE_KEY);
}, $array);
print_r($out);
Output:
Array
(
[FL_1] => Array
(
[MIC_13] => Array
(
[SP_16] => 4
)
)
[FL_2] => Array
(
[MIC_13] => Array
(
[SP_17] => 4
)
)
[FL_3] => Array
(
[MIC_13] => Array
(
[SP_18] => 1
)
)
)
Demo on 3v4l.org
I have seen strange behavior that I don't quite get. I do the following:
$array = [
'a' => [
'a1' => [
'a11' => 1,
'a12' => 2
],
'a2' => [
'a21' => 3,
'a22' => 4
],
],
'b' => [
'b1' => [
'b11' => 1,
'b12' => 2
],
'b2' => [
'b21' => 3,
'b22' => 4
],
],
];
foreach ($array as $strLevel1 => &$arrLevel1)
{
foreach ($arrLevel1 as $strLevel2 => &$arrLevel2)
{
foreach ($arrLevel2 as $strLevel3 => &$varLevel3)
{
$varLevel3 = 0;
}
}
}
echo '<pre>';
var_dump($array);
echo '</pre>';
foreach ($array as $strLevel1 => $arrLevel1)
{
}
echo '<pre>';
var_dump($array);
echo '</pre>';
The result is as follows:
array(2) {
["a"]=>
array(2) {
["a1"]=>
array(2) {
["a11"]=>
int(0)
["a12"]=>
int(0)
}
["a2"]=>
array(2) {
["a21"]=>
int(0)
["a22"]=>
int(0)
}
}
["b"]=>
&array(2) {
["b1"]=>
array(2) {
["b11"]=>
int(0)
["b12"]=>
int(0)
}
["b2"]=>
&array(2) {
["b21"]=>
int(0)
["b22"]=>
&int(0)
}
}
}
array(2) {
["a"]=>
array(2) {
["a1"]=>
array(2) {
["a11"]=>
int(0)
["a12"]=>
int(0)
}
["a2"]=>
array(2) {
["a21"]=>
int(0)
["a22"]=>
int(0)
}
}
["b"]=>
&array(2) {
["a1"]=>
array(2) {
["a11"]=>
int(0)
["a12"]=>
int(0)
}
["a2"]=>
array(2) {
["a21"]=>
int(0)
["a22"]=>
int(0)
}
}
}
As you can see, in the first output everything is ok. But in the second one, the b-named branch of the array is replaced by the a-named branch. This is because of the referencing I did. If I put a "&" before $arrLevel1 in the last loop, it works again.
Why is that? Am I doing something wrong with the references? Or should I don't use them at all and do array manipulation only fully qualified without any reference?
Thanks in advance.
Maybe you should unset the reference to $arrLevel1 after your loop, till you reused the var for the second loop.
foreach ($array as $strLevel1 => &$arrLevel1)
{
foreach ($arrLevel1 as $strLevel2 => &$arrLevel2)
{
foreach ($arrLevel2 as $strLevel3 => &$varLevel3)
{
$varLevel3 = 0;
}
}
}
// remove reference
unset($arrLevel1);
echo '<pre>';
var_dump($array);
echo '</pre>';
foreach ($array as $strLevel1 => $arrLevel1)
{
}
echo '<pre>';
var_dump($array);
echo '</pre>';
A way to come around unset is to use unique names for your loop variables or - if you want to loop over the same array again - just also use an reference loop var.
foreach ($array as $strLevel1 => &$arrLevel1)
{
foreach ($arrLevel1 as $strLevel2 => &$arrLevel2)
{
foreach ($arrLevel2 as $strLevel3 => &$varLevel3)
{
$varLevel3 = 0;
}
}
}
// also use a reference
foreach ($array as $strLevel1 => &$arrLevel1)
{
}
Most of the time, it might be simplier to just don't use references or move the loop in an "atomic" function which just does the manipulation and returns the result.
i'm trying to sort an array by the value of a sub-key in DESC order but I'm stuck.
I've could make it with ksort but it was in ascending order..
Here's my array :
array_by_lang => array(
[no] => array(
[3-1] => array(//some informations),
[3-10] => array(//informations),
[3-7] => array(//informations),
[5-1] => array(//informations)
)
)
what i want to obtain is something like :
array_by_lang => array(
[no] => array(
[5-1] => array(//informations),
[3-10] => array(//some informations),
[3-7] => array(//informations),
[3-1] => array(//informations)
)
)
Is that possible ? Thanks a lot
I think, you need "reversing natural sort by key". Just with array_multisort and array_reverse (see also natsort):
$array_by_lang = array(
'no' => array(
'3-1' => array('info_1'),
'3-10' => array('info_2'),
'3-7' => array('info_3'),
'5-1' => array('info_4'),
)
);
array_multisort(array_keys($array_by_lang['no']),SORT_NATURAL, $array_by_lang['no']);
$array_by_lang['no'] = array_reverse($array_by_lang['no']); // reverse natural order - "DESC"
var_dump($array_by_lang);
Output
array(1) {
["no"]=>
array(4) {
["5-1"]=>
array(1) {
[0]=>
string(6) "info_4"
}
["3-10"]=>
array(1) {
[0]=>
string(6) "info_2"
}
["3-7"]=>
array(1) {
[0]=>
string(6) "info_3"
}
["3-1"]=>
array(1) {
[0]=>
string(6) "info_1"
}
}
}
This might help -
$a = array(
'3-1' => array('//some informations'),
'3-10' => array('//informations'),
'3-7' => array('//informations'),
'5-1' => array('//informations')
);
## Array for keys
$temp= array();
foreach(array_keys($a) as $v) {
$t = explode('-', $v);
$temp[$t[0]][] = $t[1];
}
## Sort the keys
foreach($temp as &$ar) {
rsort($ar);
}
krsort($temp);
## Final array
$final= array();
foreach($temp as $k => $f) {
foreach($f as $v) {
$key = $k . '-' . $v;
$final[$key] = $a[$key];
}
}
var_dump($final);
Output
array(4) {
["5-1"]=>
array(1) {
[0]=>
string(14) "//informations"
}
["3-10"]=>
array(1) {
[0]=>
string(14) "//informations"
}
["3-7"]=>
array(1) {
[0]=>
string(14) "//informations"
}
["3-1"]=>
array(1) {
[0]=>
string(19) "//some informations"
}
}
DEMO
I have the following array:
array(2) {
[0] => array(4) {
["presentation_id"] => int(143)
["user_id"] => int(2)
["session_id"] => int(46)
["submission_id"] => int(190)
}
[1] => array(4) {
["presentation_id"] => int(144)
["user_id"] => int(2)
["session_id"] => int(46)
["submission_id"] => int(190)
}
What I want is to have an array consisting of just certain keys of this array, for example:
array(2) {
[0] => array(4) {
["presentation_id"] => int(143)
["user_id"] => int(2)
}
[1] => array(4) {
["presentation_id"] => int(144)
["user_id"] => int(2)
}
Any ideas?
$array = array_map(function ($arr) {
return array_intersect_key($arr, array_flip(array('presentation_id', 'user_id')));
}, $array);
Important to note that this syntax requires PHP 5.3+.
For other versions:
foreach ($array as &$arr) {
$arr = array_intersect_key($arr, array_flip(array('presentation_id', 'user_id')));
}
I'd suggest this over unsetting unwanted keys (as suggested by others) if you definitely want to restrict the array to certain elements. If you add more elements to the array in the future you won't need to update this code, but you'd have to unset more elements that you may not want.
Try:
$newArray = array_map(function ($innerArray) {
unset($innerArray['session_id'], $innerArray['submission_id'] /*, and so on*/);
return $innerArray;
}, $oldArray);
please use foreach and unset the key which you want to remove. Like
foreach($data as $key=> $row){
unset[$key] ["session_id"] ;
}
This question already has answers here:
How to re-index the values of an array in PHP? [duplicate]
(3 answers)
Closed 2 years ago.
I have an array:
$array = array(1,2,3,4,5);
If I were to dump the contents of the array they would look like this:
array(5) {
[0] => int(1)
[1] => int(2)
[2] => int(3)
[3] => int(4)
[4] => int(5)
}
When I loop through and unset certain keys, the index gets all jacked up.
foreach($array as $i => $info)
{
if($info == 1 || $info == 2)
{
unset($array[$i]);
}
}
Subsequently, if I did another dump now it would look like:
array(3) {
[2] => int(3)
[3] => int(4)
[4] => int(5)
}
Is there a proper way to reset the array so it's elements are Zero based again ??
array(3) {
[0] => int(3)
[1] => int(4)
[2] => int(5)
}
Try this:
$array = array_values($array);
Using array_values()
Got another interesting method:
$array = array('a', 'b', 'c', 'd');
unset($array[2]);
$array = array_merge($array);
Now the $array keys are reset.
Use array_splice rather than unset:
$array = array(1,2,3,4,5);
foreach($array as $i => $info)
{
if($info == 1 || $info == 2)
{
array_splice($array, $i, 1);
}
}
print_r($array);
Working sample here.
Just an additive.
I know this is old, but I wanted to add a solution I don't see that I came up with myself. Found this question while on hunt of a different solution and just figured, "Well, while I'm here."
First of all, Neal's answer is good and great to use after you run your loop, however, I'd prefer do all work at once. Of course, in my specific case I had to do more work than this simple example here, but the method still applies. I saw where a couple others suggested foreach loops, however, this still leaves you with after work due to the nature of the beast. Normally I suggest simpler things like foreach, however, in this case, it's best to remember good old fashioned for loop logic. Simply use i! To maintain appropriate index, just subtract from i after each removal of an Array item.
Here's my simple, working example:
$array = array(1,2,3,4,5);
for ($i = 0; $i < count($array); $i++) {
if($array[$i] == 1 || $array[$i] == 2) {
array_splice($array, $i, 1);
$i--;
}
}
Will output:
array(3) {
[0]=> int(3)
[1]=> int(4)
[2]=> int(5)
}
This can have many simple implementations. For example, my exact case required holding of latest item in array based on multidimensional values. I'll show you what I mean:
$files = array(
array(
'name' => 'example.zip',
'size' => '100000000',
'type' => 'application/x-zip-compressed',
'url' => '28188b90db990f5c5f75eb960a643b96/example.zip',
'deleteUrl' => 'server/php/?file=example.zip',
'deleteType' => 'DELETE'
),
array(
'name' => 'example.zip',
'size' => '10726556',
'type' => 'application/x-zip-compressed',
'url' => '28188b90db990f5c5f75eb960a643b96/example.zip',
'deleteUrl' => 'server/php/?file=example.zip',
'deleteType' => 'DELETE'
),
array(
'name' => 'example.zip',
'size' => '110726556',
'type' => 'application/x-zip-compressed',
'deleteUrl' => 'server/php/?file=example.zip',
'deleteType' => 'DELETE'
),
array(
'name' => 'example2.zip',
'size' => '12356556',
'type' => 'application/x-zip-compressed',
'url' => '28188b90db990f5c5f75eb960a643b96/example2.zip',
'deleteUrl' => 'server/php/?file=example2.zip',
'deleteType' => 'DELETE'
)
);
for ($i = 0; $i < count($files); $i++) {
if ($i > 0) {
if (is_array($files[$i-1])) {
if (!key_exists('name', array_diff($files[$i], $files[$i-1]))) {
if (!key_exists('url', $files[$i]) && key_exists('url', $files[$i-1])) $files[$i]['url'] = $files[$i-1]['url'];
$i--;
array_splice($files, $i, 1);
}
}
}
}
Will output:
array(1) {
[0]=> array(6) {
["name"]=> string(11) "example.zip"
["size"]=> string(9) "110726556"
["type"]=> string(28) "application/x-zip-compressed"
["deleteUrl"]=> string(28) "server/php/?file=example.zip"
["deleteType"]=> string(6) "DELETE"
["url"]=> string(44) "28188b90db990f5c5f75eb960a643b96/example.zip"
}
[1]=> array(6) {
["name"]=> string(11) "example2.zip"
["size"]=> string(9) "12356556"
["type"]=> string(28) "application/x-zip-compressed"
["deleteUrl"]=> string(28) "server/php/?file=example2.zip"
["deleteType"]=> string(6) "DELETE"
["url"]=> string(45) "28188b90db990f5c5f75eb960a643b96/example2.zip"
}
}
As you see, I manipulate $i before the splice as I'm seeking to remove the previous, rather than the present item.
I use $arr = array_merge($arr); to rebase an array. Simple and straightforward.
100% working for me ! After unset elements in array you can use this for re-indexing the array
$result=array_combine(range(1, count($your_array)), array_values($your_array));
Late answer but, after PHP 5.3 could be so;
$array = array(1, 2, 3, 4, 5);
$array = array_values(array_filter($array, function($v) {
return !($v == 1 || $v == 2);
}));
print_r($array);
Or you can make your own function that passes the array by reference.
function array_unset($unsets, &$array) {
foreach ($array as $key => $value) {
foreach ($unsets as $unset) {
if ($value == $unset) {
unset($array[$key]);
break;
}
}
}
$array = array_values($array);
}
So then all you have to do is...
$unsets = array(1,2);
array_unset($unsets, $array);
... and now your $array is without the values you placed in $unsets and the keys are reset
In my situation, I needed to retain unique keys with the array values, so I just used a second array:
$arr1 = array("alpha"=>"bravo","charlie"=>"delta","echo"=>"foxtrot");
unset($arr1);
$arr2 = array();
foreach($arr1 as $key=>$value) $arr2[$key] = $value;
$arr1 = $arr2
unset($arr2);