PHP数组搜索 - 如何在另一个数组中找到数组键的匹配?

时间:2014-11-29 15:18:05

标签: php arrays multidimensional-array php-5.5

如何在另一个数组中找到数组的匹配项?

例如,

数组1,

Array
(
    [0] => Array
        (
            [parent_id] => 4 // the lookup key
            [count] => 7
        )

    [1] => Array
        (
            [parent_id] => 5 // the lookup key
            [count] => 2
        )

)

数组2,

Array
(
    [0] => Array
        (
            [router] => xxx
            [path] => xxx
            [plugin] => xxx
        )

    [1] => Array
        (
            [router] => xxx
            [path] => xxx
            [plugin] => xxx
            [parent_id] => 4 // the match 
        )

    [2] => Array
        (
            [router] => xxx
            [path] => xxx
            [plugin] => xxx
        )

    [3] => Array
        (
            [router] => xxx
            [path] => xxx
            [plugin] => xxx
            [parent_id] => 5 // the match 
        )

    [4] => Array
        (
            [router] => xxx
            [path] => xxx
            [plugin] => xxx
        )
)

我追求的结果,

Array
(
    [0] => Array
        (
            [router] => xxx
            [path] => xxx
            [plugin] => xxx
            [parent_id] => 4
            [count] => 7
        )

    [1] => Array
        (
            [router] => xxx
            [path] => xxx
            [plugin] => xxx
            [parent_id] => 5
            [count] => 2
        )

)

1 个答案:

答案 0 :(得分:1)

试试这个..

array_column函数将从第二个数组返回parent_id,array_search函数将匹配array1和array2中的两个parent_id,而array_merge函数将使用匹配的parent_ids合并两个数组。

未经测试,请原谅任何小的语法错误。

$array1 = array(); // this is your first array in your example
$array2 = array(); // this is your second array in your example
$result = array(); // this is what you're looking for

foreach ($array1 as $row) {
  $result[] = array_merge($row, $array2[array_search($row["parent_id"], array_column($array2,"parent_id")];
}