数组到嵌套的Json

时间:2016-08-13 05:09:52

标签: php arrays json

我尝试将一些数据转换为json。数据如下所示:

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

我想得到的输出是:

{
  "KJS0001":{
    "Name":"Mike",
    "Address":["Cairo","Egypt"]
  },
  "KHO0001":{
    "Name":"Jhon",
    "Address":["Paris","France"]
  }
}

由于嵌套属性的数量不同而且它的id索引也是如何生成Address(包含来自address1和address2数组的数据)。任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:2)

这是一种可能的解决方案,通过创建新数组并使用json_encode

<?php
    $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);
?>

如果列已修复,则不需要$one中提到的列名。

现场演示:https://eval.in/621908

输出是:

 [ 
   {"KJS0001":{"Name":"Mike","Address":["Cairo","Egypt"]}},
   {"KHO0001":{"Name":"Jhon","Address":["Paris","France"]}}
 ]