Grouping and Merging array in PHP

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

     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
            )
        );
        //result will be here
        $result = array();
    
        foreach ($array as $key => $value) {
            //check if we have keys group or names to avoid errors
            if(!isset($value['group']) || !isset($value['names']))
                continue;
    
            //make a key in result array if its not exist
            if(!isset($result[$value['group']]))
            {
                $result[$value['group']] = $value['names'];
            }
            else
            {
                //add a values to key if it exists
                $result[$value['group']] = array_merge($result[$value['group']], 
                    $value['names']);
                //filter same values
                $result[$value['group']] = array_values(array_unique($result[$value['group']]));
            }
        }
        print_r($result);
    

提交回复
热议问题