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

I am sending JSON to a PHP script. I do this through jQuery ajax call. I think the ajax part works quite well. But here is 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); } }); } 

In my PHP page, I want to skip decoded JSON and save the data in my db. As soon as I get the values ​​from the array, I can save them. But I can not get them out of the array at the moment! I cannot find an explanation of access to a multidimensional array in PHP that I can understand. Here is my PHP:

 $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 someone point me in the right direction to access values ​​from an array? Thanks for that in advance!

+4
source share
3 answers

you cannot access this array if it is indexed with 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 will be like this:

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

but of course you can use print_r() your array so that you know how you get 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

+2
source

the problem with the string is the slashes that do the following:

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

let me know if that worked.

0
source

The answers above have helped me a lot. But what ultimately worked is analyzed as follows:

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

Source: https://habr.com/ru/post/1484752/


All Articles