PHP匹配2个数组之间的值不是同一个键

时间:2016-03-21 10:36:04

标签: php arrays

我已经进行了研究,并没有为此提供任何解决方案。所以最后的想法是来到Stackoverflow并提出问题。

我有2个数组如下:

BigArray

Array
(
    [0] => Array
        (
            [id] => 1
            [category_name] => Accountancy
            [category_name_vi] => Kế toán
            [category_id] => 1
        )

    [1] => Array
        (
            [id] => 2
            [category_name] => Armed forces
            [category_name_vi] => Quân đội
            [category_id] => 2
        )

    [2] => Array
        (
            [id] => 3
            [category_name] => Admin & Secretarial
            [category_name_vi] => Thư ký & Hành chính
            [category_id] => 3
        )

    [3] => Array
        (
            [id] => 4
            [category_name] => Banking & Finance
            [category_name_vi] => Tài chính & Ngân hàng
            [category_id] => 4
        )
)

和SmallArray:

Array
(
    [0] => Array
        (
            [id] => 7
            [category_id] => 2
            [jobseeker_id] => 1
        )

    [1] => Array
        (
            [id] => 8
            [category_id] => 3
            [jobseeker_id] => 1
        )
)

好的,现在我想要将category_id链接中的每个SmallArray与来自category_name的{​​{1}}分别匹配,输出我只需要BigArray之间的匹配值SmallArray其中BigArray category_id为关键,而SmallArray category_name的价值如下:

匹配数组:

BigArray

到目前为止,我已尝试过array_intersect,2个foreach循环但没有运气。任何建议将非常感激:(

由于

1 个答案:

答案 0 :(得分:1)

这应该这样做:

foreach ($smallArray as $smallKey => $smallElement) {
    foreach ($bigArray as $bigKey => $bigElement) {
        if ($bigElement['id'] == $smallElement['category_id']) {
            $smallArray[$smallKey] = array(
                $bigElement['id'] => $bigElement['category_name'],
            );
            break; // for performance and no extra looping
        }
    }
}

在这些循环之后,您可以在$smallArray中获得所需的内容。