简体   繁体   English

PHP json_encode输出格式

[英]php json_encode output format

I need to convert the following array from php to this format 我需要将以下数组从php转换为这种格式

(php format) [["A","1"],["B","1"],["C","1"],["D","-1"],["E","-1"],["F","-1"]]

to this format 此格式

"A": 1,
        "B": 1,
        "C": 1

etc 等等

I'm getting the array using 我正在使用数组

$data[] = array($field1, $field2);

and it's being echoed in php using 它正在使用PHP在echo中

echo json_encode($data);

I need to parse this data using javascript for jverctormap 我需要使用JavaScript为jverctormap解析此数据

any ideas how I could do this? 有什么想法我该怎么做?

I will give you a short snippet to make this transformation on Javascript: 我将给您一个简短的代码片段,以对Javascript进行此转换:

var jsonFromArray = {};
arrayToBeTransformed.forEach(function(v){
    jsonFromArray[v[0]] = v[1];
});
console.log(jsonFromArray);

Where arrayToBeTransformed has this value: 其中arrayToBeTransformed具有以下值:

[["A","1"],["B","1"],["C","1"],["D","-1"],["E","-1"],["F","-1"]] [[“ A”,“ 1”],[“ B”,“ 1”],[“ C”,“ 1”],[“ D”,“-1”],[“ E”,“-1 “],[” F“,”-1“]]

Probably easiest to send the array in its natural format, then process it client-side. 可能最容易以其自然格式发送数组,然后在客户端对其进行处理。

Javascript Java脚本

var data = [["A","1"],["B","1"],["C","1"],["D","-1"],["E","-1"],["F","-1"]];

var output = {};

data.forEach(function(a) {
    output[a[0]] = Number(a[1]);
});

/*
output will be 
{
    "A": 1,
    "B": 1,
    "C": 1,
    "D": -1,
    "E": -1,
    "F": -1
}
*/

In php just change 在PHP中只需更改

$data[] = array($field1, $field2);

To

$data[$field1] =  $field2;

No sense sending it in a format you don't need and having to convert it 以您不需要的格式发送并转换它毫无意义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM