我希望将键和值与2个数组组合,但这两个数组都不相等。$array1 = array("1","2","3","4","5");$array2 = array("apple","banana","","dog","");$key_value = array_combine($array1,$array2);输出为:array_combine():两个参数应具有相同数量的元素但是我需要在下面输出像print_r($key_value);array(5) { [1]=> string(5) "apple" [2]=> string(6) "banana" [3]=> string(8) "No Value" [4]=> string(3) "dog" [5]=> string(8) "No Value" }如果为 null,如何执行此操作,请插入“无值”文本。
2 回答
德玛西亚99
TA贡献1770条经验 获得超3个赞
你可以通过循环来做:foreach
$res = [];
foreach($array1 as $ind=>$num){
$res[$num] = $array2[$ind] === "" ? "No Value" : $array2[$ind];
}
print_r($res);
输出:
Array
(
[1] => apple
[2] => banana
[3] => No Value
[4] => dog
[5] => No Value
)
慕妹3242003
TA贡献1824条经验 获得超6个赞
使用和array_map()array_combine()
<?php
$array1 = array("1","2","3","4","5");
$array2 = array("apple","banana","","dog","");
$array2 = array_map(function($v){
return (empty($v)) ? "No Value" : $v;
},$array2);
$key_value = array_combine($array1,$array2);
print_r($key_value);
https://3v4l.org/CY4ku
- 2 回答
- 0 关注
- 110 浏览
添加回答
举报
0/150
提交
取消