I have the following (simplified) array:
$myArray = array(
0=> array(
'userid' => '12',
'favcolor' => 'green'
),
1=> array(
'userid' => '62',
'favcolor' => 'orange'
),
2=> array(
'userid' => '12',
'favcolor' => 'red'
),
3=> array(
'userid' => '62',
'favcolor' => 'blue'
),
)
I would like to merge the array by the common userid value present and keep the fav colour information. Other methods i've tried only keep the first favcolor value from the array. Seems simple enough, but not been able to find an quick solution for this.
Expected output:
$myArray = array(
0=> array(
'userid' => '12',
'favcolor' => array('green', 'red')
),
1=> array(
'userid' => '62',
'favcolor' => array('orange', 'blue')
),
)
Is this possible without working with another array to compare against?
Here we are using simple foreach
for merging and achieving expected result, By using userid
of this array as the key
. here we are using array_values
to remove those key.
<?php
ini_set('display_errors', 1);
$myArray = array(
0=> array(
'userid' => '12',
'favcolor' => 'green'
),
1=> array(
'userid' => '62',
'favcolor' => 'orange'
),
2=> array(
'userid' => '12',
'favcolor' => 'red'
),
3=> array(
'userid' => '62',
'favcolor' => 'blue'
),
);
$result=array();
foreach($myArray as $value)
{
//check for previous existence of key in resultant array
//if key not exist then put value on that key and using favcolor as array
if(!isset($result[$value["userid"]]))of key in a array.
{
$result[$value["userid"]]=array("userid"=>$value["userid"],"favcolor"=>array($value["favcolor"]));
}
//if key already exists then just adding favcolor values to that key
else
{
$result[$value["userid"]]["favcolor"][]=$value["favcolor"];
}
}
print_r(array_values($result));
Output:
Array
(
[0] => Array
(
[userid] => 12
[favcolor] => Array
(
[0] => green
[1] => red
)
)
[1] => Array
(
[userid] => 62
[favcolor] => Array
(
[0] => orange
[1] => blue
)
)
)