I want to merge a multidimensional array values if the values are the same under the ‘u’,’v’ and ‘w’ keys.
$myarray = array (
'0' =>
array (
'u' => '30',
'v' => '16',
'w' => '22',
'x' => '30',
'y' => '16',
'z' => '22',
),
'1' =>
array (
'u' => '32',
'v' => '25',
'w' => '1',
'x' => '30',
'y' => '16',
'z' => '22',
),
'2' =>
array (
'u' => '30',
'v' => '16',
'w' => '22',
'x' => '54',
'y' => '96',
'z' => '2',
),
'3' =>
array (
'u' => '30',
'v' => '16',
'w' => '22',
'x' => '3',
'y' => '1',
'z' => '6',
)
);
I want the output to be as below:
//OUTPUT
array (
'0' =>
array (
'u' => '30',
'v' => '16',
'w' => '22',
'x' => '30,54,3',
'y' => '16,96,1',
'z' => '22,2,6',
),
'1' =>
array (
'u' => '32',
'v' => '25',
'w' => '1',
'x' => '30',
'y' => '16',
'z' => '22',
)
)
This is what I have tried to do so far, which has not worked out for me.
<?php
$n = 0;
$output = [];
foreach ($myarray as $row) {
$prevkey = key(array_slice($output, -1,1,true));// get previous array key
if(array_key_exists('0', $output)){
if($output[$prevkey]['u'] == $row['u'] && $output[$prevkey]['v'] == $row['v'] && $output[$prevkey]['w'] == $row['w'] ){
echo "yes <br>";
$output += $row;
}
}else{
$output[] = $row;
}
$n++;
}
var_dump($output);
?>
3
Answers
You can create some specific array for that purpose with its specific indexes, based on those 3 values. For ex.:
Output:
Demo
You can use
array_reduce
:Working example
This grouping by multiple columns can be done in a single loop without needing to reindex at the end if reference variables are pushed into the result array.
vsprintf()
is an easy way to create a delimited string fron the first 3 values in each row — if you need to explicitly name the identifying keys because they are not reliably first in the rows, then you can manually access them to building the composite key.Concatenation is only performed if a group is encountered more than once.
Code: (Demo)