如何使用PHP数组创建JSON?

时间:2017-01-31 20:57:51

标签: php arrays json

我有一个小问题,无法继续前进。

我写了这个PHP代码:

 $d=array();
 foreach(range(0, 3) as $rs) {
    foreach(range(0, 5) as $c){

       //here is working php code to generate '$randomRs' by '$rs' and '$c' vars..

       $d[] = array('rs'.$rs => array('c'.$c => $randomRs));

    }
}
echo json_encode($d);

现在JSON输出为:

[{"rs0":{"c0":"bl"}},{"rs0":{"c1":"pl"}},{"rs0":{"c2":"bl"}},{"rs0":{"c3":"pl"}},{"rs0":{"c4":"pl"}},{"rs0":{"c5":"wd1"}},{"rs1":{"c0":"lk"}},{"rs1":{"c1":"gr"}},{"rs1":{"c2":"lk"}},{"rs1":{"c3":"gr"}},{"rs1":{"c4":"lk"}},{"rs1":{"c5":"gr"}},{"rs2":{"c0":"u1"}},{"rs2":{"c1":"u1"}},{"rs2":{"c2":"u1"}},{"rs2":{"c3":"wt"}},{"rs2":{"c4":"u1"}},{"rs2":{"c5":"u1"}},{"rs3":{"c0":"u1"}},{"rs3":{"c1":"u1"}},{"rs3":{"c2":"u1"}},{"rs3":{"c3":"u1"}},{"rs3":{"c4":"cl"}},{"rs3":{"c5":"ir"}}]

哪个错了。我需要实现这个结果(不要介意值):

{
"rs0":{
   "c0":"pl",
   "c1":"pl",
   "c2":"pl",
   "c3":"pl",
   "c4":"pl"
},
"rs1":{
   "c0":"pl",
   "c1":"pl",
   "c2":"pl",
   "c3":"pl",
   "c4":"pl"
}
and so on...

请告诉我我做错了什么,我该如何完成?

1 个答案:

答案 0 :(得分:1)

$d=array();
foreach(range(0, 3) as $rs) {
    foreach(range(0, 5) as $c){

        //here is working php code to generate '$randomRs' by '$rs' and '$c' vars..

        $d['rs'.$rs]['c'.$c] = $randomRs;

    }
}