PHP:编码嵌套的JSON数组问题

时间:2016-09-18 11:20:36

标签: php arrays json

我很困惑写这个,我怎么能实现这个类似的输出。我从早就开始做json编码。但这个对我来说是不同的。

 [{
        type: 'pie',
        name: 'Browser share',
        innerSize: '40%',
        data: [
            ['Firefox',   10.38],
            ['IE',       56.33],
            ['Chrome', 24.03],
            ['Safari',    4.77],
            ['Opera',     0.91],
            {//over here i can't get this braces
                name: 'Proprietary or Undetectable',
                y: 0.2,
                dataLabels: {
                    enabled: false
                }
            }
        ]
    }]

这是我的代码,

$percentage = array();
$arr2 = new stdClass();
$arr2->type = 'pie';
$arr2->name = 'Browser share';
$arr2->innerSize = '40%';
while($azSoc = mysql_fetch_assoc($az)){ 
    $arr2->data[] = array("".$azSoc['criteria_name']."", $azSoc['crit_score_percentage']);
}
$arr2->name = 'Porperty ok';
$arr2->y = 0.2;
$arr2->dataLabels[] = array('enable',false);
array_push($percentage, $arr2);
echo json_encode( $percentage);

我的代码输出给了我,

[{"type":"pie","name":"Porperty ok","innerSize":"40%","data":[["tes","25"],
["awdawdas","25"],["awdawd","25"],["ehhehe","25"]],"y":0.2,"dataLabels":
[["enable",false]]}]

2 个答案:

答案 0 :(得分:2)

你想要实现的是无效的json。您需要在名为some_name的数组中创建一个新的出现,然后将该对象加载到该出现中

$percentage = array();

$arr2 = new stdClass();
$arr2->type = 'pie';
$arr2->name = 'Browser share';
$arr2->innerSize = '40%';
while($azSoc = mysql_fetch_assoc($az)){ 
    $arr2->data[] = array("".$azSoc['criteria_name']."", $azSoc['crit_score_percentage']);
}

$t = new stdClass();
$t->name = 'Porperty ok';
$t->y = 0.2;
$t->dataLabels = array('enable',false);
$arr2->data['some_name'] = $t;

$percentage[] = $arr2;

//dont know where $cat came from I assume its a larger oject you are building
echo json_encode( $cat);   

答案 1 :(得分:1)

而不是array('enable',false);它应该是array('enable' => false);