Search code examples
phparraysmultidimensional-arraytransposearray-column

Restructure multidimensional array of column data into multidimensional array of row data


I have the following associative array of column data:

$where = array(
    'id'=>array(
        12,
        13,
        14
    ),
    'date'=>array(
        '1999-06-12',
        '2000-03-21',
        '2006-09-31'
    )
);

I need to transpose / rotate the structure to be an array of rows (with merged column data assigned to their respective row). I don't need the column names in the result.

Expected output:

$comb = array(
    array(12, '1999-06-12'),
    array(13, '2000-03-21'),
    array(14, '2006-09-31')
);

Solution

  • As Kris Roofe stated in his deleted answer, array_column is indeed a more elegant way. Just be sure to put it into some kind of a foreach loop, similar to what Sahil Gulati showed you. For example, like this:

    $result = array();
    
    foreach($where['id'] as $k => $v)
    {
      $result[] = array_column($where, $k);
    }
    

    The var_dump output of $result is exactly what you're looking for

    array(3) {
      [0]=>
      array(2) {
        [0]=>
        int(12)
        [1]=>
        string(10) "1999-06-12"
      }
      [1]=>
      array(2) {
        [0]=>
        int(13)
        [1]=>
        string(10) "2000-03-21"
      }
      [2]=>
      array(2) {
        [0]=>
        int(14)
        [1]=>
        string(10) "2006-09-31"
      }
    }