PHP多维数组动态

时间:2018-08-30 04:44:45

标签: php json

这是静态多维数组,我转换为json。

$mailmsg = array(
  'type'=> 'line',
  'data' =>   array(
      'labels' => array("1","2","3","4","5"),  
      'datasets' => array(array("label"=>"A","fill"=>"false","yAxisID"=>"A","borderColor"=>"#bae755","data"=>array(100, 96, 84, 76, 69)),array("label"=>"B","fill"=>"false","yAxisID"=>"B","borderColor"=>"#55bae7","data"=>array(1, 1, 1, 1, 0)),array("label"=>"C","fill"=>"false","yAxisID"=>"C","borderColor"=>"#e755ba","data"=>array(5, 15, 10, 10, 0)))),
  ' '=>array("scales"=>array("yAxes"=>array(array("scaleLabel"=>array("display"=>"true","labelString"=>"Prn1"),"id"=>"A","type"=>"linear","position"=>"left"),array("scaleLabel"=>array("display"=>"true","labelString"=>"Prn2"),"id"=>"B","type"=>"linear","position"=>"left"),array("scaleLabel"=>array("display"=>"true","labelString"=>"Prn3"),"id"=>"C","type"=>"linear","position"=>"left")))
));
echo $json = json_encode((object)$mailmsg, JSON_NUMERIC_CHECK);

结果:

{
    "type": "line",
    "data": {
        "labels": ["1","2","3","4","5"],
        "datasets": [{
            "label": "A",
            "fill": "false",
            "yAxisID": "A",
            "borderColor": "#bae755",
            "data": [100, 96, 84, 76, 69]
        }, {
            "label": "B",
            "fill": "false",
            "yAxisID": "B",
            "borderColor": "#55bae7",
            "data": [1, 1, 1, 1, 0]
        }, {
            "label": "C",
            "fill": "false",
            "yAxisID": "C",
            "borderColor": "#e755ba",
            "data": [5, 15, 10, 10, 0]
        }]
    },
    "options": {
        "scales": {
            "yAxes": [{
                "scaleLabel": {
                    "display": "true",
                    "labelString": "Prn1"
                },
                "id": "A",
                "type": "linear",
                "position": "left"
            }, {
                "scaleLabel": {
                    "display": "true",
                    "labelString": "Prn2"
                },
                "id": "B",
                "type": "linear",
                "position": "left"
            }, {
                "scaleLabel": {
                    "display": "true",
                    "labelString": "Prn3"
                },
                "id": "C",
                "type": "linear",
                "position": "left"
            }]
        }
    }
}

我需要在静态数组上方使用foreach动态更改。

1 个答案:

答案 0 :(得分:1)

只需将引用传递给数组中的特定数据即可

foreach($mailmsg['data']['datasets'] as $key => $value){

}