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

create nested array with PHP

i have a problem here. so, i try to make nested array for my json using php and this is what im getting

[
  {
    "ID":"3301",
    "NAME":"cust 01",
    "ID2":"33"
   },
   {
    "ID":"3301",
    "NAME":"cust 01",
    "ID2":"33"
   }
 ]

but i want to make it like this

[
  {
    "ID":"3301",
    "NAME":"cust 01",
     "attribut":
     [
       {
         "ID2":"33"
       }
     ]
   },
   {
    "ID":"3301",
    "NAME":"cust 01",
    "attribut":
     [
       {
         "ID2":"33"
       }
     ]
   }
 ]

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

//Query
$sql = 'select * from mytable';
$query = mysqli_query($con,$sql);
while($data=mysqli_fetch_array($query,MYSQLI_ASSOC))
$output[]=$data;
// json
echo json_encode($output);

can someone help me?

>Solution :

Move the ID2 value into the nested array in the attribut key before pushing onto the $output array.

while($data=mysqli_fetch_array($query,MYSQLI_ASSOC)) {
    $data['attribut'] = [['ID2' => $data['ID2']];
    unset($data['ID2']);
    $output[]=$data;
}
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