我有一个像这样的数组:
array:3 [▼
0 => {#472 ▼
+"component_id": 3
+"supplier_id": 1
+"volumes": "100:1.5000,207:1.0100,500:0.8000,1000:0.4000"
}
1 => {#474 ▼
+"component_id": 3
+"supplier_id": 2
+"volumes": "10000:0.2000"
}
2 => {#475 ▼
+"component_id": 4
+"supplier_id": 2
+"volumes": "100:0.1000,500:0.0700"
}
]
我想爆炸''部分并创建它自己的数组,最终结束:
[
"component_id" => 4
"supplier_id" => 2
"volumes" => array:3 [▼
100 => "0.1000",
500 => "0.0700"
]
]
我已经尝试了一些事情,这是我到目前为止最接近的事情(使用Laravel 5.2):
$components = DB::select(
'SELECT component_id, supplier_id,
GROUP_CONCAT(volume, \':\', unit_cost) AS volumes
FROM component_supplier
GROUP BY CONCAT(component_id, supplier_id)'
);
foreach ($components as $component) {
$exploded = explode(",",$component->volumes);
array_push($components, $exploded);
}
哪个更近了!但是只需将正确的格式附加到数组的末尾 - 这就是我对array_push的期望,我想:)
array:6 [▼
0 => {#472 ▼
+"component_id": 3
+"supplier_id": 1
+"volumes": "100:1.5000,207:1.0100,500:0.8000,1000:0.4000"
}
1 => {#474 ▼
+"component_id": 3
+"supplier_id": 2
+"volumes": "10000:0.2000"
}
2 => {#475 ▼
+"component_id": 4
+"supplier_id": 2
+"volumes": "100:0.1000,500:0.0700"
}
3 => array:4 [▼
0 => "100:1.5000"
1 => "207:1.0100"
2 => "500:0.8000"
3 => "1000:0.4000"
]
4 => array:1 [▼
0 => "10000:0.2000"
]
5 => array:2 [▼
0 => "100:0.1000"
1 => "500:0.0700"
]
]
所以我努力爆炸它,把它变成一个键=>值格式,然后(最重要的是),在正确的位置将其推回到数组中。
感谢您的帮助:)
答案 0 :(得分:0)
foreach ($components as $component) {
$volumesList = explode(',', $component->volumes);
$volumesDictionary = [];
foreach ($volumesList as $listItem) {
list($key, $value) = explode(':', $listItem);
$volumesDictionary[$key] = $value;
}
$component->volumes = $volumesDictionary;
}
说明:
项目用逗号分隔,键值对用冒号分隔。所以我们必须爆炸两次。将键与值分开后,我们将它们添加到字典中。最后,我们想用一个关联数组替换序列化字典,所以不是调用array_push
(它总是将项目附加到数组的末尾,不到项目到最后一个项目< em> in 数组)我们只用新创建的字典替换$component->volumes
字符串。
答案 1 :(得分:0)
看起来你需要两次爆炸。这样的事情。
foreach ($components as $component) {
$exploded = explode(",",$component->volumes);
foreach($exploded as $item)
{
$ex_item = explode(':', $item);
$components[$ex_item[0]] = $ex_item[1];
}
}