在PHP上使用if(in_array)加入两个数组

时间:2019-01-17 10:30:25

标签: php arrays

我有两个数组,我想将它们组合

对于数组1

Array
(
[57] => Array
    (
        [id] => 1
        [name] => Data1
    )

[61] => Array
    (
        [id] => 2
        [name] => Data2
    )

[65] => Array
    (
        [id] => 3
        [name] => Data3
    )

[70] => Array
    (
        [id] => 4
        [name] => Data4
    )

[73] => Array
    (
        [id] => 5
        [name] => Data5
    )

)

对于数组2

Array
(
[58] => Array
        (
        [id] => 1
        [detail] => Data 1.1
    )

[59] => Array
    (
        [id] => 1
        [detail] => Data 1.2
    )

[62] => Array
    (
        [id] => 2
        [detail] => Data 2.1
    )

[63] => Array
    (
        [id] => 2
        [detail] => Data 2.2
    )

[64] => Array
    (
        [id] => 2
        [detail] => Data 2.3
    )

[66] => Array
    (
        [id] => 3
        [detail] => Data 3.1
    )

[67] => Array
    (
        [id] => 3
        [detail] => Data 3.2
    )

[68] => Array
    (
        [id] => 3
        [detail] => Data 3.3
    )

[71] => Array
    (
        [id] => 4
        [detail] => Data 4.1
    )

[74] => Array
    (
        [id] => 5
        [detail] => Data 5.1
    )

[75] => Array
    (
        [id] => 5
        [detail] => Data 5.2
    )

[76] => Array
    (
        [id] => 5
        [detail] => Data 5.3
    )

[77] => Array
    (
        [id] => 5
        [detail] => Data 5.4
    )

[78] => Array
    (
        [id] => 5
        [detail] => Data 5.5
    )

)

我想基于ID合并它们,如果数组2中的ID与数组1中的ID相同,那么Array2将加入array1,或者我想让系统知道数据1是否具有:子数据1 ,数据2具有:子数据2,依此类推

结果可能是这样

Data1
    subData 1.1
    subData 1.2


Data2
    subData 2.1
    subData 2.2
    subData 2.3


Data3
    subData 3.1
    subData 3.2
    subData 3.3


Data4
    subData 4.1


Data5
    subData 5.1
    subData 5.2
    subData 5.3
    subData 5.4
    subData 5.5

我尝试使用if(in_array),但出现错误。

for($i=1;$i<=count($arrL1);$i++){
    if (in_array($i, $arrL2[$i])){
        echo $character->Data;
        echo $character->subData;
    }
 }

错误消息

  

消息:未定义的偏移量:1

     

消息:in_array()期望参数2为数组,给定null

0 个答案:

没有答案