php - array_combine或array_merge?

时间:2012-04-16 19:19:53

标签: php array-merge

我确信这对于精通php的人来说很容易,但我犯了重载我的大脑的错误,所以现在我真的很困惑我是否应该使用array_combine,array_merge或其他东西...我一直在谷歌搜索和阅读php.net 4小时,我想我只是让自己更加困惑......

基本上,我只是想在保持键的同时组合一个数组?

//Here are the original arrays
[field_sreference] => Array
    (
        [0] => Array
            (
                [nid] => 28
            )

        [1] => Array
            (
                [nid] => 28
            )

        [2] => Array
            (
                [nid] => 29
            )
    )

[field_idelta] => Array
    (
        [0] => Array
            (
                [value] => 0
            )

        [1] => Array
            (
                [value] => 1
            )

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

[field_iswitch] => Array
    (
        [0] => Array
            (
                [value] => 0
            )

        [1] => Array
            (
                [value] => 0
            )

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

//Here is what I'm trying to achieve:

[combinedarray] => Array
        (
            [0] => Array
                (
                    [nid] => 28
                    [idelta] => 0
                    [iswitch] => 0

                )

            [1] => Array
                (
                    [nid] => 28
                    [idelta] => 1
                    [iswitch] => 0
                )

            [2] => Array
                (
                    [nid] => 29
                    [idelta] => 0
                    [iswitch] => 0
                )
        )

2 个答案:

答案 0 :(得分:3)

你可以通过简单地迭代数组来解决这个O(n)...

$combinedarray = array();
$len = count($field_sreference);
for ($i = 0; $i < $len; $i++) {
    $combinedarray[] = array("nid" => $field_sreference[$i]['nid'], 
                             "idelta" => $filed_idelta[$i]['value'], 
                             "iswitch" => $field_iswitch[$i]['value']);
}

这假设,3个数组的长度都相同。

答案 1 :(得分:0)

有点快速输入,但这应该有效:

$result = array();
foreach ($arrays as $array)
{
    foreach ($array as $index => $data)
    {
        $result[$index] += $data;        
    }
}

由于您没有以某种简单的形式提供某些输入数组,因此您需要自己测试它。让我们说它是伪代码,我把它留在这里作为练习。 +运算符是array union operator