简体   繁体   中英

php json_encode output format

I need to convert the following array from php to this format

(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

echo json_encode($data);

I need to parse this data using javascript for jverctormap

any ideas how I could do this?

I will give you a short snippet to make this transformation on Javascript:

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

Where arrayToBeTransformed has this value:

[["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

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

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

To

$data[$field1] =  $field2;

No sense sending it in a format you don't need and having to convert it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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