繁体   English   中英

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

[英]PHP array search - How to find the match of the key of an array in another array?

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

例如,

阵列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
        )

)

尝试这个 ..

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

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

$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")];
}

暂无
暂无

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

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