Arief DWS Arief DWS - 10 months ago 36
PHP Question

Array to nested Json

I try to convert some data into a json. The data looks like this:

$one = ["ID","Name","Address1","Address2"];
$two = ["KJS0001","Mike","Cairo","Egypt"];
$three = ["KHO0001","Jhon","Paris","France"];

The Output I want to get is:


Since the amount of nested attributes varies and its indexed with id also how to make Address (contain data from address1 and address2 array). Can anyone help me?


This is one possible solution, By creating new array and use json_encode

    $data = array();
    //$columns = ["ID","Name","Address1","Address2"];
    $data[] = ["KJS0001","Mike","Cairo","Egypt"];
    $data[] = ["KHO0001","Jhon","Paris","France"];
    $result = array();
    foreach($data as $value){
      $result[] = [$value[0] => ["Name"=>$value[1],"Address"=>[$value[2],$value[3]] ] ];
    echo json_encode($result);

Column name, you mentioned in $one is not needed if columns are fixed.

Live demo :

Output is :