Php 如果键不存在,则进行数组合并
如果数组中不存在密钥,我尝试合并两个数组,但我无法完成此操作。我该怎么办?这就是我尝试过的:Php 如果键不存在,则进行数组合并,php,arrays,Php,Arrays,如果数组中不存在密钥,我尝试合并两个数组,但我无法完成此操作。我该怎么办?这就是我尝试过的: array (size=3) // name of the array $exchange 'purchase' => string '1' (length=1) 'agriculture' => string '1' (length=1) array (size=6) // name of the array $fixed 'purchase' => stri
array (size=3) // name of the array $exchange
'purchase' => string '1' (length=1)
'agriculture' => string '1' (length=1)
array (size=6) // name of the array $fixed
'purchase' => string '0' (length=1)
'ICT' => string '0' (length=1)
'agriculture' => string '0' (length=1)
'entertainment' => string '0' (length=1)
'goods and service' => string '0' (length=1)
'other' => string '0' (length=1)
foreach($fixed as $keys=>$values){
if(!in_array($values, $exchange, true)){
array_push($exchange, $keys);
}
}
我得到这个结果:
array (size=7)
'ICT' => string '1' (length=1)
0 => string 'purchase' (length=8)
1 => string 'ICT' (length=3)
2 => string 'agriculture' (length=11)
3 => string 'entertainment' (length=13)
4 => string 'goods and service' (length=17)
5 => string 'other' (length=5)
但我想:
array (size=7)
'ICT' => string '1' (length=1)
'purchase' => string '0' (length=8)
'agriculture' => string '0' (length=11)
'entertainment' => string '0' (length=13)
'goods and service' => string '0' (length=17)
'other' => string '0' (length=5)
这有几个问题:
将搜索给定数组的值,而不是键,因此在这种情况下,您只需检查数组$variable
中是否存在值“0”。我假设您想检查密钥是否已经存在
array\u push
将新值推送到下一个可用键中for($fixed as $key=>$value)
{
if(!isset($exchange[$key])) // Check if the key exists
{
$exchange[$key] = $value; // Add the new key -> value pair.
}
}
根据您想要的结果,您可以通过多种方式完成:
foreach($fixed as $key=>$values){
if(!isset($exchange[$key])){
$exchange[$key]=values;
}
}
或
或
尝试使用
数组\u merge
()
试试这个:
foreach ($fixed as $keys => $values) {
if (! array_key_exists($keys, $exchange)) {
$exchange[$keys] = $values;
}
}
它检查键$keys
是否在$exchange
中不存在,并将其与其值($values
)相加
或者,只需将整个foreach()
块替换为:
$exchange = $exchange + $fixed;
添加的$exchange+$fixed
将$exchange
中的键(及其值)添加到$fixed
中,但不在$exchange
中。然后,组合的数组存储在$exchange
中
也请阅读。它解释了代码错误的位置。第一个数组显示
size=3
,但您只复制/粘贴了两个项目。。。请修复。使用非数字键时,需要小心使用array\u merge
。后一个参数中的值将覆盖前一个参数中的任何值。出于这个原因,您可能希望翻转答案中的参数,因为$exchange
中已经存在的任何键都将被$fixed
中的默认值覆盖。您提到的第三个选项是无效的解决方案,array\u merge也会更新现有键。第一种变体是多行,看起来很难看。howewer第二个是最好的解决方案,它实现了用户在标题中提到的功能。array\u key\u exists($key,$exchange)
比isset($exchange[$key])
更好。也许$exchange[$key]
是NULL
,OP希望这样。
$result = array_merge($array1, $array2);
foreach ($fixed as $keys => $values) {
if (! array_key_exists($keys, $exchange)) {
$exchange[$keys] = $values;
}
}
$exchange = $exchange + $fixed;