我有两个数组。一个数组由 Id &另一个数组由值和&组成。键。例如。我有一个名为 Fruit_id 的变量,它包含:
array(
'fruit_id' => array(
(int) 0 => '3',
(int) 1 => '4'
)
)
和另一个名为 fruits 的数组,其中包括:
array(
'values' => array(
(int) 1 => ' Apple',
(int) 2 => 'Banana',
(int) 3 => 'Orange',
(int) 4 => 'Mango'
),
'keys' => array(
(int) 0 => (int) 1,
(int) 1 => (int) 2,
(int) 2 => (int) 3,
(int) 3 => (int) 4
)
)
所以,基于 fruit_id ,我希望 Orange & 芒果存储在变量中。如何实现这一目标?
答案 0 :(得分:0)
根据我的理解,您可以尝试下面的代码
$fruits = array();
foreach ($array1['fruit_id'] as $key1 => $value1)
{
foreach ($array2['values'] as $key2 => $value2)
{
if ($value1 == $key2)
{
$fruits[$value1] = $value2;
}
}
}
print_r($fruits);
这将返回数组([3] =>橙色[4] =>芒果)
如果这有助于您解决或需要进行任何更改,请告知我们
答案 1 :(得分:0)
即使不使用任何循环,您也可以轻松实现这一目标。请改用array_filter()。
$array1 = array("fruit_id" => array(3, 4));
$array2 = array(
"values" => array(1 => "Apple",2 => "Banana",3 => "Orange", 4 => "Mango"),
"keys" => array(1,2,3,4)
);
/* Filter elements from $array2['values'] whose keys are present in $array1['fruit_id'] */
$result = array_filter($array2['values'], function($v, $k) use ($array1){
return in_array($k, $array1['fruit_id']);
}, ARRAY_FILTER_USE_BOTH);
echo implode(' & ', $result); // Convert array to string separated by '&'