如何在 php 中的 array_combine 的 KEY=> VALUE 中填充空值
How to fill a empty value in KEY=> VALUE for array_combine in php
我希望将 Key 和 Value 与 2 个数组组合,但两个数组不相等。
$array1 = array("1","2","3","4","5");
$array2 = array("apple","banana","","dog","");
$key_value = array_combine($array1,$array2);
输出为:
array_combine(): Both parameters should have an equal number of elements
但我需要下面的输出像
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"
}
如果为空,如何执行此操作,插入 "no value" 文本。
您可以通过 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
)
使用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);
我希望将 Key 和 Value 与 2 个数组组合,但两个数组不相等。
$array1 = array("1","2","3","4","5");
$array2 = array("apple","banana","","dog","");
$key_value = array_combine($array1,$array2);
输出为:
array_combine(): Both parameters should have an equal number of elements
但我需要下面的输出像
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"
}
如果为空,如何执行此操作,插入 "no value" 文本。
您可以通过 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
)
使用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);