I have an array mentioned below.
$array = array(
'0' => array(
'names' => array(0 => 'Apple'),
'group' => 1
),
'1' => array(
'names' => array(0 => 'Mango'),
'group' => 1
),
'2' => array(
'names' => array(0 => 'Grapes'),
'group' => 1
),
'3' => array(
'names' => array(0 => 'Tomato'),
'group' => 2
),
'4' => array(
'names' => array(0 => 'Potato'),
'group' => 2
)
);
I want the result in such a way that the if the value of the array key "group" is same then the values of the key "names" should be merged. I want the output mentioned below.
$array = array(
'0' => array(
'names' => array(0 => 'Apple', 1 => 'Mango', 2 => 'Grapes'),
'group' => 1
),
'1' => array(
'names' => array(0 => 'Tomato', 1 => 'Potato'),
'group' => 2
)
);
You could iterate the array and store everything in a separate array to the group. Afterwards, you can create the output array in the format you want it, like so:
A perfect usage example for the PHP function
array_reduce()
:The code uses
array_reduce()
to iteratively build a new array that contains the expected values.The callback function creates the group, if needed, then merges the names of the processed item into the existing group in the resulting array.
The array generated using
array_reduce()
is indexed using the values ofgroup
, in the order they appear in the input array. For the posted array, they keys will be1
and2
. If you don't care about the keys then remove the call toarray_values()
to gain a little improvement in speed and readability.The function
array_values()
drops the keys and returns an array indexed using sequential numerical keys starting with zero (as the one listed in the question).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 thenames
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)
Output:
You can use
array_values()
to remove the temporary associative keys from the result array.