检查array2中的array1值

时间:2011-07-22 14:26:36

标签: php multidimensional-array

在php中使用以下两个不同的数组:

Array1
(
    [0] => Array
        (
            [id] => 1
            [name] => William
        )

    [1] => Array
        (
            [id] => 2
            [name] => Bob
        )

    [2] => Array
        (
            [id] => 3
            [name] => Michael
        )

)
Array2
(
    [0] => Array
        (
            [id] => 11128
            [name] => John
        )

    [1] => Array
        (
            [id] => 11127
            [name] => Adam
        )

    [2] => Array
        (
            [id] => 11126
            [name] => Andrew
        )

    [3] => Array
        (
            [id] => 11125
            [name] => William
        )

    [4] => Array
        (
            [id] => 11124
            [name] => Bob
        )

)

我可以以某种方式找到匹配的name,因此输出将如下:

Array1 (1, id:2) matches Array2 (4, id:11124) with name: Bob
Array1 (0, id:1) matches Array2 (3, id:11125) with name: William

抱歉,如果不清楚

2 个答案:

答案 0 :(得分:3)

你总是可以尝试一个简单的foreach循环:

<?php
foreach($array1 as $key1=>$value1) {
    foreach($array2 as $key2=>$value2) {
        if($value1['name'] === $value2['name']) {
            sprintf('Array1 (%d, id:%d) matches Array2 (%d, id:%d) with name: %s', $key1, $value1['id'], $key2, $value2['id'], $value1['name']);
        }
    }
}
?>

答案 1 :(得分:1)

foreach($array1 as $i=>$x){
  foreach($array2 as $k=>$y){
    if($x['name'] == $y['name']){
      echo "Array1 ($i, id:{$x['id']}) matches Array2 ($k, id:{$y['id']}) with name: {$x['name']}\n";
      break;
    }
  }
}