【问题标题】:PHP array search - How to find the match of the key of an array in another array?PHP数组搜索 - 如何在另一个数组中找到一个数组的键的匹配项?
【发布时间】:2014-11-29 15:18:04
【问题描述】:

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

例如,

数组 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 变成一个关联数组,其中父 ID 为键。然后循环遍历数组 2,为每个元素添加相应的计数。
  • 谢谢。我可以想象这部分是如何完成的 - Turn array 1 into an associative array where the parent ID is the key. 但不确定第二部分 - ...adding the corresponding count to each element. 你能举个例子吗?
  • 请自己努力,这不是免费的编码服务。试试看,这就是你的学习方法。如果您无法使其正常工作,请发布您的代码,我们将帮助您修复它。

标签: php arrays multidimensional-array php-5.5


【解决方案1】:

试试这个..

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    • 2011-10-22
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多