Postingan lainnya
Bagaimana membuat nested foreach multiple di codeigniter
Saya coba menampilkan produk berdasarkan kategori di dalam sub kategori, tapi sepertinya tidak menghasilkan output yang saya inginkan.
Struktur tabel nya seperti ini:
Testing kode nya:
function product() {
$category = $this->db->query("select * from tb_product_category");
foreach($category as $key) {
$subcategory = $this->db->query("select * from tb_product_sub_category where id_product_category = '".$key->id_product_category."'");
foreach($subcategory as $cat) {
$product = $this->db->query("select * from tb_product where id_product_category = '".$key->id_product_category."'");
$key->sub_category = array(
'sub_category_name' => $cat
);
foreach($product as $prod) {
$key->product = array(
'product' => $prod
);
}
}
}
echo json_encode($category);
}
Saya ingin hasil nya seperti dibawah ini:
{
"data": [
{
"id_product_category": "1",
"category_name": "Sembako",
"sub_category": [
{
"sub_category_name": "Beras",
"product": [
{
"id_product": "3",
"product_name: "BerasKita Premium 5 Kg",
"price": "65000",
}
]
},
{
"sub_category_name": "Gula",
"product": [
{
"id_product": "5",
"product_name: "Gula ManisKita 1 Kg",
"price": "12500",
}
]
},
{
"sub_category_name": "Minyak",
"product": [
{
"id_product": "1",
"product_name: "Minyak Goreng Vipco 1 lt",
"price": "12500",
},
{
"id_product": "4",
"product_name: "Minyak GorengKita 1 Ltr",
"price": "12500",
}
]
},
{
"sub_category_name": "Terigu",
"product": [
{
"id_product": "7",
"product_name: "Tepung Ketan Rose Brand",
"price": "10500",
}
]
}
],
},
{
"id_product_category": "2",
"category_name": "Bumbu",
"sub_category": [
{
"sub_category_name": "Masakan",
"product": [
{
"id_product": "24",
"product_name: "Garam Dapur Himalayan Salt",
"price": "19500",
}
]
},
{
"sub_category_name": "Kecap",
"product": [
{
"id_product": "23",
"product_name: "Bango Kecap Manis Refill 550 ml",
"price": "23000",
}
]
}
],
},
]
}
Mohon bantuan nya..
0
1 Jawaban:
Kayanya agan lupa ngasih result di akhir querynya,
coba diubah kaya gini :
<pre> function product() { $category = $this->db->query("select * from tb_product_category")->result();
foreach($category as $key) {
$subcategory = $this-&gt;db-&gt;query("select * from tb_product_sub_category where id_product_category = '".$key-&gt;id_product_category."'")-&gt;get()-&gt;result();
foreach($subcategory as $cat) {
$product = $this-&gt;db-&gt;query("select * from tb_product where id_product_category = '".$key-&gt;id_product_category."'")-&gt;result();
$key-&gt;sub_category = array(
'sub_category_name' =&gt; $cat
);
foreach($product as $prod) {
$key-&gt;product = array(
'product' =&gt; $prod
);
}
}
}
echo json_encode($category);
} </pre>
0