Postingan lainnya
cara group data json
hai semua salam kenal
saya sedang ingin menampilkan table produk yang dikelompokan berdasarkan id supplier
data jsonnya sepert ini
{"inventory":{"query":[{"key":"a27239eaec62ba6405f5e9f0fb715bd5"}],"status":[{"code":202,"description":"ok"}],"results":[{"id":"177","user_id":"87","supplier_id":"6","product_id":"36","product_name":"Tripod octopus","varian_id":"141","varian_name":"Varian Acak","jumlah":"1"},{"id":"178","user_id":"87","supplier_id":"8","product_id":"37","product_name":"Pembersih Mata Buah Nanas","varian_id":"140","varian_name":"Acak","jumlah":"3"},{"id":"179","user_id":"87","supplier_id":"8","product_id":"42","product_name":"Gunting dahan pohon","varian_id":"135","varian_name":"gunting dahan","jumlah":"1"}]}}
saat ini saya tampilkan data nya tanpa pengelompokan
seperti ini
$datainventory = json_decode($jsondata, true);
$totalRecord = count($datainventory['inventory']['results']);
for ($j=0; $j < $totalRecord; $j++)
{
echo $datainventory['inventory']['results'][$j]['supplier_id'];
echo $datainventory['inventory']['results'][$j]['product_name'];
}
adakah yang tahu cara mengeompokan data json saya tadi sehingga nantinya akan seperti ini
supplier A supplier B
product 1 product 1
product 2 product 2
product 3 product 3
dan seterusnya, mohon bantuannya , terima kasih sebelumnya
1 Jawaban:
<div>Saya mencoba membuat script seperti ini, di sini index array inventory adalah sebagai supplier_id nya, dan menyimpan array berupa string berupa nama barang..<br>ini bukan best practice, namun bisa membantu</div><div><br></div><pre><?php
$data = [ [ "id_barang" => 1, "nama_barang" => "kulkas", "supplier_id" => 1 ], [ "id_barang" => 2, "nama_barang" => "handphone", "supplier_id" => 2 ], [ "id_barang" => 5, "nama_barang" => "laptop", "supplier_id" => 1 ], [ "id_barang" => 4, "nama_barang" => "panci", "supplier_id" => 2 ], [ "id_barang" => 3, "nama_barang" => "tv", "supplier_id" => 1 ], ];
$inventory = []; $inserted_supplier = [];
for($i = 0; $i < 5; $i++) { $supplier_id = $data[$i]['supplier_id']; $nama_barang = $data[$i]['nama_barang'];
if(!in_array($supplier_id, $inserted_supplier)) {
array_push($inserted_supplier, $supplier_id);
$inventory[$supplier_id] = [$nama_barang];
} else {
array_push($inventory[$supplier_id], $nama_barang);
}
}
var_dump($inventory);</pre>