Grouping and Merging array in PHP

前端 未结 4 1484
挽巷
挽巷 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:46

    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:

    $groups = array();
    foreach($array as $subArray) {
        if (!array_key_exists($subArray['group'], $groups)) {
            $groups[$subArray['group']] = array();
        }
        $groups[$subArray['group']] = array_merge($groups[$subArray['group']], $subArray['names']);
    }
    
    $result = array();
    foreach($groups as $groupId => $group) {
        $result[] = array(
            'names' => $group,
            'group' => $groupId,
        );
    }
    
    print_r($result);
    

提交回复
热议问题