Home > other >  Grouping some array into one , but keep the different data
Grouping some array into one , but keep the different data

Time:09-05

Sorry if this questions looks a basic one, but just this got me overnight

How to transform this :

[
    [
        'id' => 2,
        'role_id' => 2,
        'name' => 'PABLO',
        'sections' => 'FINANCE',
        'department' => 'FATP',
     ],
    [
       'id' => 2,
       'role_id' => 2,
       'name' => 'PABLO',
       'sections' => 'ACCOUNTING',
       'department' => 'FATP',
    ]
]

to This :

[
    [
        'id' => 2,
        'role_id' => 2,
        'name' => 'PABLO',
        'sections' => ['FINANCE','ACCOUNTING']
        'department' => 'FATP',
    ],
]

CodePudding user response:

You can use the following code:

     $initial_array = array(
        array('id' => 2,
            'role_id' => 2,
            'name' => 'PABLO',
            'sections' => 'FINANCE',
            'department' => 'FATP'
        ),
        array(
            'id' => 2,
            'role_id' => 2,
            'name' => 'PABLO',
            'sections' => 'ACCOUNTING',
            'department' => 'FATP'
        )
     );

     $grouped_array = array();
     foreach($initial_array as $element){
        $code = $element['id'].'&'.$element['role_id'].'&'.$element['name'].'&'.$element['department']; // you can set fewer elements if you like.
        $grouped_array[$code][] = $element['sections'];
     }

     $final_array = array();
     foreach($grouped_array as $code => $sections_array){
        $code_table = explode('&', $code);
        $final_array[] = array(
            'id' => $code_table[0],
            'role_id' => $code_table[1],
            'name' => $code_table[2],
            'sections' => $sections_array,
            'department' => $code_table[3]
        );
     }

     echo '<pre>';
     print_r($final_array);

It prints the following:

Array
(
    [0] => Array
        (
            [id] => 2
            [role_id] => 2
            [name] => PABLO
            [sections] => Array
                (
                    [0] => FINANCE
                    [1] => ACCOUNTING
                )

            [department] => FATP
        )

)
  • Related