[英]How to append to an array key's value php
Let's say I have an array like this:假设我有一个这样的数组:
[["code1": '528'], ["code2": '292'], ["code1": '108']]
I am looping through the array to check if a specific key exists.我正在遍历数组以检查特定键是否存在。 If it doesn't then I am adding it to another array:
如果没有,那么我将它添加到另一个数组中:
$arr[$codename] = $code
However, if the key already exists, then I want to append the $code
value to the existing key's values.但是,如果键已经存在,那么我想将
$code
值附加到现有键的值中。 I'm not sure how to do this part.我不知道如何做这部分。
I want the new array to look like this:我希望新数组看起来像这样:
[["code1": '528', '108'], ["code2", '292']]
You can try:你可以试试:
$array = [['code1' => 528], ['code2' => 292], ['code1' => 108]];
$newArray = [];
foreach ($array as $value) {
$newArray[array_key_first($value)][] = $value[array_key_first($value)];
}
print_r($newArray);
Result:结果:
Array
(
[code1] => Array
(
[0] => 528
[1] => 108
)
[code2] => Array
(
[0] => 292
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.