如何在PHP

时间:2017-05-29 13:27:36

标签: php arrays multidimensional-array

我有两个数组:

$one = Array
(
    [0] => stdClass Object
        (
            [id] => 2
            [name] => Southampton
        )

    [1] => stdClass Object
        (
            [id] => 4
            [name] => Manchester United F.C
        )

)

$two = Array
(
    [0] => stdClass Object
        (
            [number] => 25555
            [slice_1] => 4
            [slice_2] => 4
            [slice_3] => 2
            [slice_4] => 4
            [status] => Published
        )

)

我想输出,如果数组$two->slice_1与数组$one->id相同而不是输出$one->name

例如:

$two[0]->slice_1(4)与$one[0]->id(4)比较将导致曼彻斯特联队F.C。

因为数组$one$two将包含多个数组。请不要回答这个问题:

if($two[0]->slice_1 == $one[1]->id){echo $one[0]->name;}

我在这里,无法想出办法。请帮忙。提前致谢

1 个答案:

答案 0 :(得分:0)

避免循环内部循环首先创建临时引用数组,然后循环第二个数组输出结果

foreach($one as $id=>$data){
   $temp[$data['id']] = $data['name'];
}
foreach($two as $secondary_id=>$secondary_data){
  echo isset($temp[$secondary_data['slice_1']]) ? $temp[$secondary_data['slice_1']] : ''; 
}