[英]It is not possible to display an array as in the example / rebuild the array PHP
有數組
$array = [
[
'code' => 'dhl',
'customer_costs' => [
22 => '1.000',
11 => '3.000',
]
],
[
'code' => 'fedex',
'customer_costs' => [
22 => '4.000',
11 => '6.000',
]
]
];
需要重建這個
array(2) {
[22]=>
array(2) {
["dhl"]=>
string(5) "1.000"
["fedex"]=>
string(5) "4.000"
}
[11]=>
array(2) {
["dhl"]=>
string(5) "3.000"
["fedex"]=>
string(5) "6.000"
}
}
我已經做了
$arr=[];
foreach ($array as $r=>$v) {
$number = array_keys($v['customer_costs']);
foreach ($number as $k) {
$arr[$k][]=[$v['code'] => $v['customer_costs'][$k]];
}
}
這是結果 在此處輸入代碼
問題:如何使它像示例中的那樣? 我已經為這項任務苦苦掙扎了 3 天
您非常接近,但您在第二個循環中添加了一個額外的數組層。 改變
$arr[$k][]=[$v['code'] => $v['customer_costs'][$k]];
至
$arr[$k][$v['code']]=$v['customer_costs'][$k];
你會得到
array(2) {
[22]=>
array(2) {
["dhl"]=>
string(5) "1.000"
["fedex"]=>
string(5) "4.000"
}
[11]=>
array(2) {
["dhl"]=>
string(5) "3.000"
["fedex"]=>
string(5) "6.000"
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.