Grouping and Merging array in PHP

前端 未结 4 1539
挽巷
挽巷 2021-01-29 09:54

I have an array mentioned below.

$array = array(
        \'0\' => array(
            \'names\' => array(0 => \'Apple\'),
            \'group\' => 1
         


        
4条回答
  •  旧时难觅i
    2021-01-29 10:37

    A perfect usage example for the PHP function array_reduce():

    $array = array_values(
        array_reduce(
            $array,
            function (array $carry, array $item) {
                // Extract the group name into a variable for readability
                // and speed; it is used several times velow
                $key = $item['group'];
                // Initialize the group if it is the first entry in this group
                if (! array_key_exists($key, $carry)) {
                    $carry[$key] = array(
                        'names' => array(),
                        'group' => $key,
                    );
                }
                // Add the new names to the group in the output array
                $carry[$key]['names'] = array_merge($carry[$key]['names'], $item['names']);
    
                // Return the partial result
                return $carry;
            },
            array()
        )
    );
    

    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 of group, in the order they appear in the input array. For the posted array, they keys will be 1 and 2. If you don't care about the keys then remove the call to array_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).

提交回复
热议问题