使用两个数组,其中一个数组的值与另一个数组的键匹配

时间:2013-09-08 22:26:44

标签: php arrays

我在类似的问题上看到了另一个问题,但我的问题似乎是截然不同的。

我有两个数组:

数组#1:

Array
(
    [1] => Baby/Juvenile
    [2] => Bedding
    [3] => Room Decor
    [4] => Bath & Potty
    [5] => Feeding
    [7] => Furniture
    [8] => Bath
    [9] => Towels
    [10] => Shower Curtains
)

数组#2

Array
(
    [1] => 5
    [2] => 7
    [3] => 9
)

我想比较这些数组,并根据第二个数组中的值从第一个数组中提取键/值对。我想要的输出是:

   Array
(
    [5] => Feeding
    [7] => Furniture
    [9] => Towels
)

我玩各种阵列功能,但似乎无法弄明白,任何提示都会非常感谢,谢谢!

1 个答案:

答案 0 :(得分:2)

<?php

    $array_one = array
    (
        '1' => 'Baby/Juvenile',
        '2' => 'Bedding',
        '3' => 'Room Decor',
        '4' => 'Bath & Potty',
        '5' => 'Feeding',
        '7' => 'Furniture',
        '8' => 'Bath',
        '9' => 'Towels',
        '10' => 'Shower Curtains'
    );

    $array_two = array
    (
        '1' => 5,
        '2' => 7,
        '3' => 9
    );

    foreach($array_two as $value)
    {
        $result[$value] = $array_one[$value];
    }

    var_dump($result);

?>

将输出

array(3) {
  [5]=>
  string(7) "Feeding"
  [7]=>
  string(9) "Furniture"
  [9]=>
  string(6) "Towels"
}