phparraysmultidimensional-arraygroupingsub-array

Group rows of a multidimensional array by one column and create deep subarrays in another column if more than one member exists in the group


I want to consolidate the data in a multidimensional array by grouping on the email column. If an email value only occurs once, I don't want to alter the meta subarray structure. However, if an email value occurs more than once, I want to deepen the product structure by creating an indexed array of product data.

Input:

$array = [
    [
        'email' => 'test@gmail.com',
        'meta' => [
            'product' => ['id' => '1', 'content' => 'This is content']
        ]
    ],
    [
        'email' => 'test2@gmail.com',
        'meta' => [
            'product' => ['id' => '2', 'content' => 'This is content']
        ]
    ],
    [
        'email' => 'test2@gmail.com',
        'meta' => [
            'product' => ['id' => '3', 'content' => 'This is content']
        ]
    ]
];

Desired output:

[0] {
    'email' => 'test@gmail.com',
    'meta' => {
              'product' => {
                            'id' => '1',
                            'content' => 'This is content'
                           }
              }
    }
[1] {
    'email' => 'test2@gmail.com',
    'meta' => {
              'product' => [0] {
                                 'id' => '2',
                                 'content' => 'This is content'
                           }
                           [1] {
                                 'id' => '3',
                                 'content' => 'This is content'
                               }
              }
    }

Solution

  • $sorted_array = [];
    $emails = [];
    $i = 0;
    foreach ($arr as $array) {
        if(!empty($array['email']) && !empty($array['meta']['product'])){
            if( in_array($array['email'], $emails)){
                $i--;
            } else {
                $emails[] = $array['email'];
            }
            $sorted_array[$i]['email'] = $array['email'];
            $sorted_array[$i]['meta']['product'][] = $array['meta']['product'];
            $i++;
        }
    }
    echo "<pre>";
    print_r($sorted_array);
    

    Hope this will help you