在 JSON 檔案中,有多個item基于相同的product_id. 我必須基于product_idand創建多維陣列items。
根據我的示例 php 代碼,product_id重復列出。結果以 php 代碼列印。
預期結果如下。
測驗資料.json
"data": [
{
"product_id": "123456",
"item": "ZAD",
"time": "15:30",
"quantity": 1
},
{
"product_id": "24534"
"item": "REST"
"time": "5:30"
"quantity": 1
},
{
"product_id": "123456"
"item": "RAD"
"time": "10:30"
"quantity": 2
}
]
測驗.php
$json = file_get_contents('testData.json');
$d_data = json_decode($json, true);
$f_data = $d_data['data'];
foreach($f_data as $data) {
$result = [
$data['product_id'],
$data['item']
]
print_r($result);
/* Array(
[0] => 123456
[1] => ZAD
)
Array(
[0] => 123456
[1] => RAD
)
Array(
[0] => 24534
[1] => REST
)
*/
}
期待結果
123456
[
ZAD
[
"time" => "15:30",
"quantity" => 1
],
RAD
[
"time" => "10:30"
"quantity" => 2
],
],
24534
[
REST
[
"time" => "5:30"
"quantity" => 1
]
]
uj5u.com熱心網友回復:
您只需要在最終陣列中同時考慮product_id和item作為子鍵:
$result = [];
foreach($f_data as $data) {
$result[$data['product_id']][$data['item']] = [
$data['time'],
$data['quantity']
];
}
print_r($result);
演示:https ://3v4l.org/sf7om
我應該注意,如果兩個專案具有相同product_id 和相同item,則此代碼將僅保留最后一個。如果這種情況適用于您,您只需要使用[]陣列的附加模式 ( ):
$result[$data['product_id']][$data['item']][] = [
$data['time'],
$data['quantity']
];
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/510085.html
標籤:php
