Search code examples
phparraysmultidimensional-arraygroupingsub-array

Change the structure of a multi-dimensional array


I have some code that creates a multi-dimensional array, but my result seems to be an array of arrays, which is not what I want. I want to flatten this array. How can I change this array result:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [2011-11-18 00:00:00] => C
                )

            [1] => Array
                (
                    [2011-11-18 00:00:00] => I
                )

            [2] => Array
                (
                    [2011-11-18 00:00:00] => S
                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [2011-11-22 00:00:00] => C
                )

            [1] => Array
                (
                    [2011-11-22 00:00:00] => S
                )

        )

)

into something that is not an "array of arrays"? Here is the code that creates the array of arrays:

$qrybilled = $this->db->query("SELECT tbltc.BILLED FROM tbltc WHERE tbltc.PN = $pn AND tbltc.Y = $taxyear AND tbltc.SCENARIO = $scenario GROUP BY BILLED");
$x = 0; $arr_billed = array();

foreach ($qrybilled->result() as $row) {
$qry = $this->db->query("SELECT tbltc.BILLED, tbltc.TC, tbltc.CAT FROM tbltc WHERE tbltc.PN = $pn AND tbltc.Y = $taxyear AND tbltc.SCENARIO = $scenario AND tbltc.BILLED = '".$row->BILLED."' GROUP BY TC");

    $tmp = array();
    foreach ($qry->result() as $row) {      
        $tmp[] = array( $row->BILLED => $row->TC);
    }
    $arr_billed[] = $tmp; 

}
$data['billed'] = $arr_billed; 

If you can suggest a better way to build the array so that it is not an "array of arrays", that would be great. Thanks for your help.

  • EDIT -

The answer from NickB worked perfectly for me and produced the following output, which is what I was looking for:

Array
(
    [2011-11-18 00:00:00] => Array
        (
            [0] => C
            [1] => I
            [2] => S
        )

    [2011-11-22 00:00:00] => Array
        (
            [0] => C
            [1] => S
        )

)

Solution

  • You can loop through all of the entries in the array to create a new array.

    $result = array();
    
    foreach( $array as $inner_array)
    {
        foreach( $inner_array as $entry)
        {
            foreach( $entry as $key => $value)
            {
                $result[ $key ][] = $value;
            }
        }
    }
    

    Output:

    array(2) {
      ["2011-11-18 00:00:00"]=>
      array(3) {
        [0]=>
        string(1) "C"
        [1]=>
        string(1) "I"
        [2]=>
        string(1) "S"
      }
      ["2011-11-22 00:00:00"]=> 
      array(2) {
        [0]=>
        string(1) "C"
        [1]=>
        string(1) "S"
      }
    }