1

这是我的交易。我有这个数组:

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
        )

)

我需要它是这样的:

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
                )

        )

)

我使用我制作的这段代码做到了:

    $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]);
        }
    }

但我认为我的代码有点愚蠢,特别是如果我有大量数据。最终我想要做的只是将每两个索引组合在一个数组中,我知道应该有比我的代码更好的东西来做,有什么建议吗?

4

3 回答 3

6

发现array_chunk()

$temp = array_chunk($data, 2);
于 2013-10-22T09:19:44.357 回答
2
$cnt = count($data);
$temp = array();
for ($i = 0; $i < $cnt; $i = $i + 2)
{
    $temp[] = array($data[$i], $data[$i+1]);
}
于 2013-10-22T09:20:32.273 回答
1

看看array_chunk

<?php
$array = array(
    array(1),
    array(2),
    array(3),
    array(4),
);

print_r(
    array_chunk($array, 2, false)
);

/*
    Array
    (
        [0] => Array
        (
            [0] => Array
            (
                [0] => 1
            )
            [1] => Array
            (
                [0] => 2
            )
        )
        [1] => Array
        (
            [0] => Array
            (
                [0] => 3
            )
            [1] => Array
            (
                [0] => 4
            )
        )
    )
*/
于 2013-10-22T09:22:58.230 回答