简体   繁体   中英

How do I convert PHP JSON to JS array

Good day,

I have this data which I got from my query on PHP its is currently a JSON Format, now I want to convert it into array so I can use it on my pdf. How can I do this?

so in order for me to use it on my javascript I used

var inventory = <?php echo json_encode($inventory); ?> ;

my JSON data :

var inv = [
{"xid":96,"xitem":"CARBOCISTEINE 500MG CAP (MYREX) BOX",
"itemId":852,
"price":3,
"mprice":3
 },
{"xid":253,"xitem":"CIPROFLOXACIN 500MG TAB (PROSELOC\/FLAMINGO)",
 "itemId":1165,
 "price":0,
 "mprice":0
 }];

I tried

var rows = <?php echo json_encode($inventory); ?> ;
var arr = $.map(rows, function(el) { return el; });

and

when I console.log(arr); I still get the object structure not the array structure that I wanted.

I also tried

var result = [];

for(var i in rows)
    result.push([i, rows [i]]);

console.log(result);

but it gives me

[ ["0",Object { xid=96,xitem="CARBOCISTEINE 500MG CAP (MYREX) BOX",itemId=852,price=3,mprice=3}],
["1",Object{etc..}]];

instead

I want it to have a structure like

[96,"CARBOCISTEINE 500MG CAP (MYREX) BOX",852,3,3], [253,"CIPROFLOXACIN 500MG TAB (PROSELOC\\/FLAMINGO)",1165,0,0]

Is there something I am missing on my code or How should I be able to do this? thanks..

You can use this:

var arr = inv.map(function (obj) {  return [obj.xid, obj.xitem, obj.itemId, obj.price, obj.mprice]})
console.log(arr);

If you do small changes to your map callback function, then it will be fine.

you can do just

class MyClass
{
    public $var1 = 'value 1';
    public $var2 = 'value 2';
    public $var3 = 'value 3';
}

$class = new MyClass();
$arr = [];

foreach($class as $key => $value) {
    $arr[] = $value;
}

echo json_encode($arr); //here's to check

in PHP - you can make a collection of object like this and iterate first oveer this collection to get result as you wanted to have

You shouldn't have to hard code the keys. The following works:

var arrayFromObject = inv.map(function (item) {
    var arr = [];
    for (var p in item) arr.push(item[p])
    return arr;
});

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