我有以下数组:
$files = ['376840000000367020', '376840000000375036', '376840000000389001'];
$arr = [];
foreach ($files as $key => $name) {
$arr[] = $name;
}
$data = [
'376840000000367020' => '5782',
'376840000000375036' => '5783',
'376840000000389001' => '5784',
];
print_r($arr);
返回:
Array ( [0] => 376840000000367020 [1] => 376840000000375036.... )
我想比较2个数组$arr
和$data
,如果在$key
中找到$arr
,则用$data
替换值,我是' m尝试获得以下输出:
Array ( [0] => 5782 [1] => 5783 .... )
我有很多要比较的数据,因此在foreach中迭代$arr
并不理想。
我将如何做到这一点?
答案 0 :(得分:1)
您可以使用array_key_exists
功能检查数组中是否存在键:
<?php
$files = ['376840000000367020','376840000000375036','376840000000389001'];
$data = array(
'376840000000367020' => '5782',
'376840000000375036' => '5783',
'376840000000389001' => '5784',
);
$arr = [];
foreach($files as $key=>$name){
if(array_key_exists($name, $data)) {
$arr[] = $data[$name];
}
}
print_r($arr);
答案 1 :(得分:0)
迭代$files
数组并检查值是否在$data
foreach ($files as &$file) {
if (isset($data[$file])) {
$file = $data[$file];
}
}
答案 2 :(得分:0)
使用array_map传递回调函数,该回调函数检查第二个数组中是否存在该值,并在该情况下返回它的值,否则返回该值。