![](/img/trans.png)
[英]PHP - How to append an array into another array with specific key and value?
[英]How to append to an array key's value php
假設我有一個這樣的數組:
[["code1": '528'], ["code2": '292'], ["code1": '108']]
我正在遍歷數組以檢查特定鍵是否存在。 如果沒有,那么我將它添加到另一個數組中:
$arr[$codename] = $code
但是,如果鍵已經存在,那么我想將$code
值附加到現有鍵的值中。 我不知道如何做這部分。
我希望新數組看起來像這樣:
[["code1": '528', '108'], ["code2", '292']]
你可以試試:
$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);
結果:
Array
(
[code1] => Array
(
[0] => 528
[1] => 108
)
[code2] => Array
(
[0] => 292
)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.