Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create nested array Json using PHP?

i have a little problem, i want to make my attribut nested, so it looks like this. can someone help me?

enter image description here

this is the code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?php
header('Content-Type: application/json');
require_once('helper_connect.php');

$query = "SELECT * FROM mytable";
$sql = mysqli_query($db_connect, $query);

if($sql){
    $result = array();
    while($row = mysqli_fetch_array($sql)){
        array_push($result, array(
            'id' => $row['id'],
            'kategori' => $row['kategori'],
            'nama' => $row['nama'],
            'deskripsi' => $row['deskripsi'],
            'berat' => $row['berat'],
            'harga' => $row['harga'],
            'gambar' => $row['gambar'],
            'stock' => $row['stock'],
            'warna' => $row['warna'],
            'ukuran' => $row['ukuran'],
            'jenis_bahan' => $row['jenis_bahan'],
            'motif' => $row['motif'],
            'penutup' => $row['penutup'],
        ));
    }
    echo json_encode(array('product' => $result));
  }
?>

>Solution :

You just need to declare an array within the outer array, and then another (associative) array within that as the first index of it:

    array_push($result, array(
        'id' => $row['id'],
        'kategori' => $row['kategori'],
        'nama' => $row['nama'],
        'deskripsi' => $row['deskripsi'],
        'berat' => $row['berat'],
        'harga' => $row['harga'],
        'gambar' => $row['gambar'],
        'stock' => $row['stock'],
        'attribut' => array(
          0 => array(
            'warna' => $row['warna'],
            'ukuran' => $row['ukuran'],
            'jenis_bahan' => $row['jenis_bahan'],
            'motif' => $row['motif'],
            'penutup' => $row['penutup']
          )
        )
    ));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading