Grouping and Merging array in PHP

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

I have an array mentioned below.

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


        
4条回答
  •  抹茶落季
    2021-01-29 10:24

    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.

提交回复
热议问题