0

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

//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?

3
  • We can't help you fix your code if you don't post it. Commented May 11, 2022 at 3:33
  • Is attribut always just an array with one element? If so, change 'ID2' => $value to 'attribut' => [['ID2' => $value]] Commented May 11, 2022 at 3:34
  • @Barmar im sorry, i already update my question with the code Commented May 11, 2022 at 3:36

2 Answers 2

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

0

like this?

$str = '[
  {
    "ID":"3301",
    "NAME":"cust 01",
    "ID2":"33"
   },
   {
    "ID":"3301",
    "NAME":"cust 01",
    "ID2":"33"
   }
 ]';
        $arr = json_decode($str,true);
        $ret =[];
        foreach ($arr as $item){
            $res = [];
            $res['ID'] = $item['ID'];
            $res['NAME'] = $item['NAME'];
            $temp['ID2'] = $item['ID2'];
            $res['attribut'][]=$temp;
            $ret[] = $res;
        }
        var_dump(json_encode($ret));

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.