创建一个多维的关联数组,其中包含来自 json 的未知数量的循环



所以,我正在接收json输入。我不知道我会收到多少输入。我知道如何将其转换为数组,但是我需要混淆数组的结构。数组目前是多维的,并且已经是关联的,但是使用了错误的关联。对我来说,它使用"标签"和"值",但我需要这两个放在一个使用"x"和"y"的关联数组中,这样我就可以在图表中使用它们。

示例 json

{
    "metingen": [
        {
            "label": "06-06-2019 13:13:38",
            "value": 25.21
        },
        {
            "label": "06-06-2019 13:51:04",
            "value": 27.69
        },
        {
            "label": "06-06-2019 13:52:04",
            "value": 27.69
        },
        {
            "label": "06-06-2019 13:53:06",
            "value": 27.61
        },
        {
            "label": "06-06-2019 13:54:08",
            "value": 27.56
        },
        {
            "label": "06-06-2019 13:55:08",
            "value": 27.55
        },
        {
            "label": "06-06-2019 13:56:09",
            "value": 27.55
        },
        {
            "label": "06-06-2019 13:57:09",
            "value": 27.53
        },
        {
            "label": "06-06-2019 14:05:12",
            "value": 28.51
        },
        {
            "label": "06-06-2019 14:06:12",
            "value": 28.53
        },
        {
            "label": "06-06-2019 14:07:13",
            "value": 28.51
        },
        {
            "label": "06-06-2019 14:08:13",
            "value": 28.51
        },
        {
            "label": "06-06-2019 14:09:14",
            "value": 28.53
        },
        {
            "label": "06-06-2019 14:10:14",
            "value": 28.52
        },
        {
            "label": "06-06-2019 14:11:15",
            "value": 28.52
        },
        {
            "label": "06-06-2019 14:12:15",
            "value": 28.54
        },
        {
            "label": "06-06-2019 14:13:16",
            "value": 28.53
        },
        {
            "label": "06-06-2019 14:14:16",
            "value": 28.48
        },
        {
            "label": "06-06-2019 14:15:17",
            "value": 28.39
        },
        {
            "label": "06-06-2019 14:16:17",
            "value": 28.37
        }
    ],
    "title": "Temperature for ICT Boven"
}

我正在使用的 PHP

$dataPoints = array();
foreach($charts as $key=> $chart)
{
    $j=0;
    $x=$chart[0]['label'];
    $y=$chart[0]['value'];
    $i=array($x,$y);
    $dataPoints[0]=$i;
}
dataPoints array
(
   array("x"=>"06-06-2019 13:13:38","y"=>25.21)//And then a lot of these arrays
)

您可以将array_map与array_combine一起使用,如下所示,

$temp['metingen'] = array_map(function ($item) {
    return array_combine(['x', 'y'], $item); // x and y are keys and label and value are values
}, $temp['metingen']);

演示

您可以将foreachjson_decode一起使用

$jToArr = json_decode($json, true);
$res = [];
foreach($jToArr['metingen'] as $key => $value){
  $res[] = ['x' => $value['label'], 'y' => $value['value']];
}
print_r($res);

工作演示