2014-02-28 61 views
0

我想創建JSON數據類似如下格式JSON陣列:使用PHP創建

{ 
    "data": [ 
     { 
      "varient": { 
       "0": "12121221", 
       "1": "22122111" 
      }, 
      "site": "google", 
      "click": "yes" 
     }, 
     { 
      "varient": { 
       "0": "33333", 
       "1": "443434" 
      }, 
      "site": "yahoo", 
      "click": "no" 
     } 
    ] 
} 

我知道json_encode用途,以創造JSON

,但我不如何創建像上面這樣的foreach和array_merge JSON格式等[PHP代碼]

我的PHP代碼

$datalist = array(); 
$datalist[] = array("site" => "google","click" => "yes"); 
$datalist[] = array("site" => "yahoo" ,"click" => "no"); 
$fulljson=array_merge($datalist); 
$return = array('data'=>$fulljson); 
echo json_encode ($return); 

但我怎麼能插入的變體光盤d ATA

的變體光盤 「:{」 0 「:」 12121221" , 「1」: 「22122111」}

+0

所以,只要創建你想要的結構。 – xdazz

+0

json_encode處理多維數組,你不需要做任何for循環 – Tim

+0

這是一個技巧; 'var_export(json_decode($ json,true));'以查看如何在php中重新創建數組結構。 –

回答

1

Som如果我正確理解了代碼,就可以這樣:

$varient["0"] = 12121221; 
$varient["1"] = 22122111; 

$data["varient"] = $varient; 
$data["site"] = "google"; 
$data["click"] = "yes"; 

$result["data"][]=$data; 


$varient["0"] = 33333; 
$varient["1"] = 443434; 

$data["varient"] = $varient; 
$data["site"] = "yahoo"; 
$data["click"] = "no"; 

$result["data"][]=$data; 

echo json_encode($result); 
0

如果我理解你的問題,你要遍歷JSON數據。使用

json_decode($json, true) 

將json轉換爲PHP數組。

0

你只是想用

json_encode(array('data'=>$your array name)); 
+0

@Melody還指定從哪裏獲取這些數據,以便我們可以解釋你。 – Ricky

+0

檢查現在編輯後....我使用Foreach循環獲取varient變量 – Me7888

+0

我認爲你必須要使用這種類型的代碼它會做你的工作echo json_encode(array('data'=> $ fulljson)); – Ricky

0

使用json_decode

$json = '{ "data": [ { "varient": { "0": "12121221", "1": "22122111" }, "site": "google", "click": "yes" }, { "varient": { "0": "33333", "1": "443434" }, "site": "yahoo", "click": "no" } ] }'; 

$object = json_decode($json); 

echo $json->data[0]->varient; 

不是100%肯定,如果這是工作,但它應該嘗試一下,告訴我。

+0

thnx重播..但如何可以結合所有數據使用foreach和array_merger – Me7888

0

使用PHP的json_encod E,是這樣的:

<?php 
$arr = array(
    array(
     "region" => "valore", 
     "price" => "valore2" 
    ), 
    array(
     "region" => "valore", 
     "price" => "valore2" 
    ), 
    array(
     "region" => "valore", 
     "price" => "valore2" 
    ) 
); 

echo json_encode($arr); 
?> 
0

您需要填充varient陣列

 $varient = array(); 
    // set the array using your for loop 
    .... 
     $varient[] = array('0'=>'value1','1'=>'value2'); 
    .... 

    $datalist = array(); 

後設置varient指數$datalist因爲你沒有在循環您的問題

 // set each index of $datalist with the appropriate index of $varient array 
    $datalist[] = array("site" => "google","click" => "yes",'varient',$varient[0]); 
    $datalist[] = array("site" => "yahoo" ,"click" => "no" ,'varient',$varient[1]); 

    $fulljson=array_merge($$datalist); 
    $return = array('data'=>$fulljson); 
    echo json_encode ($return); 
+0

我建議你使用for循環來設置'$ datalist'。它會使代碼更具可讀性並減少行數。 – anurupr