如何在foreach制作索引并将其设为json?

时间:2018-06-04 15:01:31

标签: php jquery json

我想将来自foreach的数据保存为"将数据":值命名为变量ChartVal,但我不知道怎么做我还在学习。

  <?php 
        $nim = $this->uri->segment(3);
        $chart = $this->modelpenilaian->getchart($nim);
        foreach ($chart as $ca) {
            $a[i] = "$ca->name": $ca->nilai;
        } //I know this is wrong, I just don't know the right one



    ?>
    <script>
       var chartVals = <?php echo json_encode($a[i])?>;
    //I want to save to variable chartVals

    $(function(){
      $('#chart').radarChart({
        size: [500, 400],
        step: 1,
        title: " ",
        values: {
          //"chartVals": chartVals
          //then send it to jquery value
          chartVals
        },
        showAxisLabels: true
      });
    });

2 个答案:

答案 0 :(得分:3)

您很可能需要将$ca->name数组的键设置为您想要的名称( $a=array(); foreach ($chart as $ca) { $a[$ca->name] = $ca->nilai; } )....

echo json_encode($a);

然后

values: chartVals,

将数据添加到图表时,您需要使用

gradle clean build

答案 1 :(得分:1)

这是你要找的吗?

foreach ($chart as $ca) {
    $a[$ca->name] = $ca->nilai;
} 

它为您提供了一组键:值对。要把它变成JSON,你会:

$myJSON = json_encode($a);