phparraysmultidimensional-arraygroupingsub-array

Group rows data of a 2d array by one column and push other columns into a subarray within each group


I have an array like this:

[
    ['id' => 1, 'order_sn' => 'EU/2011/04/PO/5', 'total' => 65],
    ['id' => 1, 'order_sn' => 'EU/2011/04/RS/4', 'total' => 230],
    ['id' => 1, 'order_sn' => 'EU/2011/04/RS/3', 'total' => 130],
    ['id' => 2, 'order_sn' => 'EU/2011/04/RS/2', 'total' => 100],
    ['id' => 2, 'order_sn' => 'EU/2011/04/RS/1', 'total' => 60]
];

How can I merge the rows based on shared id values and create a details subarray to hold the other column values?

Desired result:

[
    [
        'id' => 1,
        'details' => [
            ['order_sn' => 'EU/2011/04/PO/5', 'total' => 65],
            ['order_sn' => 'EU/2011/04/RS/4', 'total' => 230],
            ['order_sn' => 'EU/2011/04/RS/3', 'total' => 130]
        ]
    ]
    [
        'id' => 2,
        'details' => [
            ['order_sn' => 'EU/2011/04/RS/2', 'total' => 100],
            ['order_sn' => 'EU/2011/04/RS/1', 'total' => 60]
        ]
    ]
]


Solution

  • Try like this:

    <?php
    $result = array();
    foreach ($my_array as $v) {
      $id = $v['id'];
      $result[$id]['id'] = $id;
      $result[$id]['detail'][] = array(
        'order_sn' => $v['order_sn'],
        'total'    => $v['total'],
      );
    }