我想将 JSON 数据转换为数组

JSON数据如下:


0: {

   'row': 0,

   'col': 0,

   'value': 4.5

},

1: {

   'row': 0,

   'col': 1,

   'value': 4.3

},

2: {

   'row': 0,

   'col': 2,

   'value': 4.9

}

我想创建一个data像data[r][c] = value. 感谢您的帮助。


慕尼黑8549860
浏览 70回答 1
1回答

绝地无双

首先,您的 JSON 数据无效。确保您有有效的 json 字符串。您可以使用JSONLint等工具来验证 JSON 数据。从那里,您可以使用json_decode进行解析,然后构建您想要的任何数组结构。例如,//valid JSON$json = '[{"row":0,"col":0,"value":4.5},{"row":0,"col":1,"value":4.3},{"row":0,"col":2,"value":4.9},{"row":1,"col":1,"value":3.1}]';//parse json data$data = json_decode( $json );//a new array to hold the parsed data$parsed = [];//iterate over the json data and re-structure as desiredforeach( $data as $item ) {    //do we have a place for this row yet?    if( ! isset($parsed[$item->row]) ) {        //no array for this row, create an empty one        $parsed[ $item->row ] = [];    }    //set the value for this column    $parsed[ $item->row ][ $item->col ] = $item->value;}的输出$parsed将是:Array(    [0] => Array        (            [0] => 4.5            [1] => 4.3            [2] => 4.9        )    [1] => Array        (            [1] => 3.1        ))
打开App,查看更多内容
随时随地看视频慕课网APP