I have an array mentioned below.
$array = array(
\'0\' => array(
\'names\' => array(0 => \'Apple\'),
\'group\' => 1
By simply using the group
values as temporary associative keys, you can swiftly determine (while iterating) if you should store the whole row of data, or just append the names
value to an existing subarray.
*if your project data may contain input subarrays with more than one names
value, you should update your question to clarify this possibility. (Fringe Demo) (Fringe Demo2)
Code: (Demo)
foreach ($array as $row) {
if (!isset($result[$row['group']])) {
$result[$row['group']] = $row;
} else {
$result[$row['group']]['names'][] = $row['names'][0];
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'names' =>
array (
0 => 'Apple',
1 => 'Mango',
2 => 'Grapes',
),
'group' => 1,
),
1 =>
array (
'names' =>
array (
0 => 'Tomato',
1 => 'Potato',
),
'group' => 2,
),
)
You can use array_values()
to remove the temporary associative keys from the result array.