数组操作和重新排列

时间:2013-10-22 09:14:57

标签: php arrays

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

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

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

3 个答案:

答案 0 :(得分:6)

发现array_chunk()

$temp = array_chunk($data, 2);

答案 1 :(得分:2)

$cnt = count($data);
$temp = array();
for ($i = 0; $i < $cnt; $i = $i + 2)
{
    $temp[] = array($data[$i], $data[$i+1]);
}

答案 2 :(得分: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
            )
        )
    )
*/