Search code examples
phparraysmultidimensional-arrayduplicatesarray-merge

Convert 3d array to 2d array by merging data in each row


I need to flatten my subarrays of data to form a simpler / more shallow 2-dimensional array. Each row should become a flat, indexed array of unique values.

Input array:

$response = [
    695 => [
        0 => [
            '00:00',
            '01:00',
            '01:30',
            '03:30',
            '04:00',
        ]
    ],
    700 => [ 
        1 => [
            '00:00',
            '00:30',
            '01:00',
            '01:30',
            '02:00',
        ],
        2 => [
            '00:00',
            '00:30',
            '09:00',
            '06:30',
            '07:00',                    
        ]
    ]
]; 

My current code:

$result = array();
foreach ($response as $key => $list) {
  $result[$key] = array_merge($result, $list);
}
var_export($result);

but this doesn't give the proper result.

Expected output:

array (
  695 => 
  array (
    0 => '00:00',
    1 => '01:00',
    2 => '01:30',
    3 => '03:30',
    4 => '04:00',
  ),
  700 => 
  array (
    0 => '00:00',
    1 => '00:30',
    2 => '01:00',
    3 => '01:30',
    4 => '02:00',
    5 => '09:00',
    6 => '06:30',
    7 => '07:00',
  ),
)

Solution

  • merge the array like this:

    $result = array_map(function($v){
      $o = [];
      foreach($v as $val)
      {
        $o = array_merge($o, $val);
      }
      return array_values(array_unique($o));
    }, $array);