Search code examples
phparrays

Group array elements into pairs


I have this array:

Array // called $data in my code
(
    [0] => Array
        (
            [name] => quantity
            [value] => 0
        )

    [1] => Array
        (
            [name] => var_id
            [value] => 4
        )

    [2] => Array
        (
            [name] => quantity
            [value] => 0
        )

    [3] => Array
        (
            [name] => var_id
            [value] => 5
        )

)

which I need it to be like:

Array // called $temp in my code
(
    [0] => Array
        (
            [0] => Array
                (
                    [name] => quantity
                    [value] => 0
                )

            [1] => Array
                (
                    [name] => var_id
                    [value] => 4
                )

        )

    [2] => Array
        (
            [0] => Array
                (
                    [name] => quantity
                    [value] => 0
                )

            [1] => Array
                (
                    [name] => var_id
                    [value] => 5
                )

        )

)

and I did it using this code I made:

    $data = $_POST['data'];
    $temp = array();
    foreach($data as $key => $datum)
    {
        if($key%2 == 0)
        {
            $temp[$key] = array();
            array_push($temp[$key], $datum, $data[$key+1]);
        }
    }

But I think that my code is some kinda stupid, specially if I have a huge data. eventually what I want to do is just have each two indexes combined in one array, and I know that there should be something better than my code to do it, any suggestions?


Solution

  • Discover array_chunk()

    $temp = array_chunk($data, 2);