Home > database >  how to do a foreach looping, only on the value of 'related_product' just on key '1�
how to do a foreach looping, only on the value of 'related_product' just on key '1�

Time:06-01

<?php

    $product = [
        1 => [
            'name' => 'Doraemon',
            'img' => 'doraemon.jpg',
            'price' => 'Rp 25.000',
            'category' => 'Manga',
            'about' => 'Doraemon dikirim kembali ke masa kehidupan Nobita oleh cicit Nobita, Sewashi. Ia dikirim untuk memperbaiki kehidupan Nobita agar keturunannya merasakan kehidupan yang lebih baik. Dalam kehidupan aslinya tanpa dibantu Doraemon, Nobita sering gagal dalam pelajaran sekolahnya, gagal dalam pekerjaan, dan mempunyai masalah keuangan.',
            'related_product' => [
                ['Detective Conan', 'detective.jpg', 'Rp 25.000'],
                ['Bleach', 'bleach.jpg', 'Rp 25.000'],
                ['Crayon Shinchan', 'crayon,jpg', 'Rp 30.000'],
            ]
        ],
        2 => [
            'name' => 'Tribun Pontianak',
            'img' => 'TribunPontianak.jpg',
            'price' => 'Rp 2.000',
            'category' => 'Newspaper',
            'about' => 'Tribun Pontianak adalah sebuah surat kabar harian yang terbit di Kalimantan Barat, Indonesia. Surat kabar ini termasuk dalam grup Kompas Gramedia. Kantor pusatnya terletak di kota Pontianak. Koran ini pertama kali terbit tahun 2008.',
            'related_product' => [
                ['Pontianak Post', 'pontianak.jpg', 'Rp 2.000'],
                ['KOMPAS', 'kompas.jpg', 'Rp 2.5000'],
                ['Harian Pontianak', 'harian.jpg', 'Rp 3.000'],
            ]
        ],
        3 => [
            'name' => 'Majalah Bobo',
            'img' => 'MajalahBobo.jpg',
            'price' => 'Rp 47.000',
            'category' => 'Magazine',
            'about' => 'Majalah Bobo adalah bacaan populer anak-anak Indonesia yang terbit sejak 14 April 1973. Majalah ini adalah versi Indonesia dari majalah serupa di Belanda dengan penyesuaian isi. Di Indonesia, terdapat 2 versi Majalah Bobo.',
            'related_product' => [
                ['TRUBUS', 'Trubus.jpg','Rp 32.000'],
                ['Femina', 'Femina.jpg', 'Rp 40.500'],
                ['Tempo', 'Tempo.jpg', 'Rp 55.000'],
            ]
        ]

    ];
?>

CodePudding user response:

if you're only interested in the first array entry, you can use:

 $related_product = current($product)['related_product'];
foreach($related_product as $product_line) {
    foreach($product_line as $product_item) {
        echo $product_item;
    }
}

CodePudding user response:

first loop over the products, and within that loop loop over your related_product array, then you can loop over the occurances in the related_products arrays

foreach ($product as $prod){
    foreach( $prod['related_product'] as $related ){
        foreach( $related as $info ) {
            echo $info . ' ';
        }
        echo '<br>';
    }
}
  • Related