phpmultidimensional-arrayflatten

Flatten a multidimensional array?


I have a multidimensional array and want to break it down. Here's the array.

array
(
    [0] => array
    (
        [0] => array
        (
            [0] => 1
            [intsch_id] => 1
        )
        [1] => array
        (
            [0] => 2
            [intsch_id] => 2
        )
    )
)

And I want to break it down to

array (
    [0] => 1
    [intsch_id] => 1,
    [1] => 2
    [intsch_id] => 2
)

And this is in a dynamic query, so the results won't always be this simple. It will have the same structure as the above multidimensional array.


Solution

  • Is the result array missing two commas?
    One before each [intsch_id] key?
    Like this:

    array ( [0] => 1, [intsch_id] => 1, [1] => 2, [intsch_id] => 2)
    

    If so, it won't be possible to have multiple array values with identical keys, [intsch_id].

    However, you just want to collapse the outer array that's holding this data, that's pretty straightforward:

    $source_array = array(
        array(
            array(
                "0" => 1,
                "intsch_id" => 1
            ),
            array(
                "0" => 2,
                "intsch_id" => 2
            )
        )
    );
    echo '<pre>'; print_r($source_array); echo '</pre>';
    $return_array = $source_array[0];
    echo '<pre>'; print_r($return_array); echo '</pre>';