我有两个数组:
$mainArray = array(
['id' => 1, 'name' => 'test'],
['id' => 2, 'name' => 'news'],
['id' => 3, 'name' => 'foo'],
['id' => 4, 'name' => 'bar']...
);
$array = array(1,2,5,6,7);
我需要检查 $ mainArray 中的ID是否包含在 $ array 中,如果包含它,则需要打印该名称。我怎样才能做到这一点?
答案 0 :(得分:3)
简单!
foreach($mainArray as $arr) {
if(in_array($arr['id'], $array)) {
echo $arr['id'];
}
}
答案 1 :(得分:2)
这应该适合你:
(使用此解决方案,您有一个数组,其中id
为key
,name
为value
)
<?php
$mainArray = array(
['id' => 1, 'name' => 'test'],
['id' => 2, 'name' => 'news'],
['id' => 3, 'name' => 'foo'],
['id' => 4, 'name' => 'bar']
);
$array = array(1,2,5,6,7);
$result = array();
foreach($mainArray as $k => $v)
$result[$v["id"]] = (array_intersect($mainArray[$k], $array) ? $mainArray[$k]["name"] : "");
$result = array_filter($result);
print_r($result);
?>
输出:
Array ( [1] => test [2] => news )
你可以轻松地通过数组打印这样的事情:
array_walk($result, function($value, $key) {
echo "Key: $key Value: $value <br />";
});
//OR
foreach($result as $key => $value)
echo "Key: $key Value: $value <br />";
输出:
Key: 1 Value: test
Key: 2 Value: news