2016-08-13 225 views
1

我嘗試將某些數據轉換爲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爲索引還怎麼讓地址(包含來自地址1數據和地址2數組)。誰能幫我?

+0

究竟會有所不同?像它這樣的變量可以是$ 3,$ four..etc?或者沒有。參數id,名稱等? –

+0

基於參數ID,它嵌套到名稱,地址(地址1和地址2) – Reint

回答

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"]}} 
] 
+0

非常感謝:) – Reint