简体   繁体   English

在PHP中构建多维数组

[英]builiding a multidimentional array in php

I have got couple of arrays. 我有几个数组。

Array 1 阵列1

Array
(
    [0] => 501
    [1] => 502
    [2] => 503
    [3] => 505
)

Array 2 阵列2

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

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

)

Now my desired array structure should be 现在我想要的数组结构应该是

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

        [1] => Array
            (
                [0] => 505
                [1] => 1
            )
        [2] => Array
            (
                [0] => 501
                [1] => 0
            )
        [3] => Array
            (
                [0] => 502
                [1] => 0
            )

    ) 

My code is 我的代码是

foreach($array1 as $k => $v)
{
    if( $array2[$k][0] == $v)
    {
        $finalArr[] = array($array2[$k][0],$array2[$k][1]);
    }
    else
    {
        $finalArr[] = array($v,0);
    }


}

Now it's giving me the right array structure which I want but the value is missing for the elements which are present in both array. 现在,它为我提供了所需的正确数组结构,但是两个数组中都存在的元素的值缺失。

The issue is with this line: 问题在于此行:

if( $array2[$k][0] == $v)

$k is referring to the index of $array1, not $array2... so unless the elements in both arrays are perfectly in sync, your script will not work. $ k是指$ array1的索引,而不是$ array2 ...的索引,因此,除非两个数组中的元素完全同步,否则脚本将无法工作。

Try this: 尝试这个:

$a_vals2 = array_map(
    function ($v) { return $v[1]; },
    $array2
);
$result = $array1;
foreach (array_diff($array1, $a_vals2) as $v) {
    $result[] = array($v, 0);
}

if( $array2[$k][0] == $v) will never return true (for provided arrays) because you're checking the indexes of the arrays together. if($ array2 [$ k] [0] == $ v)永远不会返回true(对于提供的数组),因为您正在一起检查数组的索引。 For example, 503 == 501 and 505 == 502 on the second index. 例如,第二索引上的503 == 501和505 == 502。 Seems to me like your code will just make a copy of the first array (in this example). 在我看来,您的代码只会复制第一个数组(在此示例中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM