i have a little problem, i want to make my attribut nested, so it looks like this. can someone help me?
this is the code
<?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));
}
?>
My Answer:
To create a nested array in JSON using PHP, you can modify your code to include nested arrays within the main array. Here's an example of how you can nest arrays in your JSON response:
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)){
$nestedArray = 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'],
'attributes' => array(
'warna' => $row['warna'],
'ukuran' => $row['ukuran'],
'jenis_bahan' => $row['jenis_bahan'],
'motif' => $row['motif'],
'penutup' => $row['penutup']
)
);
array_push($result, $nestedArray);
}
echo json_encode(array('product' => $result));
}
?>
In this modified code, I added an 'attributes' key to the nested array, which contains the attributes 'warna', 'ukuran', 'jenis_bahan', 'motif', and 'penutup'. This creates a nested structure within the JSON response for each product.
Rate this post
3 of 5 based on 6418 votesComments