使用PHP创建JSON数组

时间:2014-02-28 08:09:57

标签: php json multidimensional-array

我想创建类似于以下格式的JSON数据:

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

我知道json_encode用于创建json

但我不知道如何创建上面的json格式,如foreach和array_merge等[PHP CODE]

我的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);

但我如何插入变量数据

变体光盘 “:{” 0 “:” 12121221" , “1”: “22122111”}

6 个答案:

答案 0 :(得分:1)

如果我正确理解代码,那就是这样:

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

答案 1 :(得分:0)

如果我理解你的问题,你想迭代JSON数据。使用

json_decode($json, true) 

将json转换为PHP数组。

答案 2 :(得分:0)

您只想使用

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

答案 3 :(得分: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%确定这是否有效,但应该尝试并告诉我。

答案 4 :(得分: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);
?>

答案 5 :(得分:0)

填充varient数组

后,您需要在$datalist中设置varient索引
     $varient = array();
     // set the array using your for loop
     ....
         $varient[] = array('0'=>'value1','1'=>'value2');
     ....

     $datalist = array();

因为你的问题中没有for循环

     // 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);