简体   繁体   中英

How to parse PHP array that has been decoded from JSON?

I am posting some JSON to a PHP script. I'm doing this through a jQuery ajax call. I think I have the ajax part working well enough. But here's the code I'm using:

var testjson = '{"statistics":[{"player_id":"12","team_id":"8","points":"19"},{"player_id":"9","team_id":"8","points":"7"}],"teams":[{"homename":"Lakers","awayname":"Heat","webid":"48","hid":"49","aid":"48"}]}';

function postGameStats() {
jQuery.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "ajax-url.php",
    data: {"data":JSON.stringify(testjson)},
    success : function(data){
        alert(data);
    }
});
}

On my PHP page, I want to loop through the decoded JSON and store the data in my db. Once I get the values out of the array, I can store them. But I can't get them out of the array at the moment! I can't seem to find an explanation of accessing a multidemensional array in PHP that I can understand. Here's my PHP so far:

$finally = json_decode($_POST['data'], true);

$size = count($finally[1]);
$i = 0;
while ($i < ($size)) {
  echo $finally[$i].['statistics'].[$i].['player_id']; 
$i = $i + 1;
}

Can anyone point me in the right direction of how to access the values from the array? Thanks so much in advance!

well you can't access that kind of array when it is indexed by keys(associative array) and not numbers so you need to use foreach()

foreach($myarray as $key => $val){
   echo $key." ".$val['innerkey'];
}

so in your case it would be like this

   foreach($finally['statistics'] as $key => $val){
      echo $val[$key]['player'];
   }

but of course you can use print_r() your array so you would know how you will access it

print_r($finally);

http://php.net/manual/en/control-structures.foreach.php

http://php.net/manual/en/function.print-r.php

http://php.net/manual/en/language.types.array.php

the problem with the stringify is the slashes doing the following will solve the issue:

$finally = json_decode(stripslashes($_POST['data']), true);

let me know if it worked out.

The answers above helped me a great deal. But what ultimately worked is parsing like follows:

echo $finally["statistics"][1]["player_id"];

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