Home > Enterprise >  PHP Get values from nested array
PHP Get values from nested array

Time:12-21

I am new to PHP and Arrays, I am trying to get the values from an array. But no matter how I'm trying to do it, I can't get the value. What am I doing wrong?

The Array:

Array ( [playerinfo] => Array ( [rank] => Godfather [cash] => € 8,520,530 [weapon] => M-16 (29000) [health] => Array ( [width] => 100 [color] => green ) [wealth] => Too rich to be true [protection] => Bulletproof Humvee [plf] => Huge [plane] => Concorde [crew] => None [pbf] => Large [ship] => None ) [character] => Array ( [crime] => Array ( [0] => 120 [1] => 69 ) [gta] => Array ( [0] => 400 [1] => 70 ) [drugs] => Array ( [0] => 120 [1] => 2528 ) [airport] => Array ( [0] => 2700 [1] => 2529 ) [oc] => Array ( [0] => 86400 [1] => 1442364 ) [tr] => Array ( [0] => 10800 [1] => 1640016011 ) [plf] => Array ( [0] => 7200 [1] => 6712 ) [kill] => Array ( [0] => 3600 [1] => 1640019611 ) ) )

The way I tried to get the info:

$AccData = json_decode($MobinfoString, true);
echo $AccData['playerinfo']['rank'].'<br/>';
echo $AccData['playerinfo']['cash'].'<br/>';

foreach ($AccData as $playerinfo) {
    echo $playerinfo['playerinfo']['rank'].'<br/>';
    echo $playerinfo['character']['gta'].'<br/>';
}

EDIT:

The json string

{"playerinfo":{"rank":"Boss","cash":"€ 5,923,712","weapon":"M-16 (4500)","health":{"width":"100","color":"green"},"wealth":"Too rich to be true","protection":"Bulletproof Humvee","plf":"Huge","plane":"Concorde","crew":"None","pbf":"Large","ship":"None"},"character":{"crime":[120,122],"gta":[400,369],"drugs":[120,2582],"airport":[2700,2582],"oc":[86400,1640020450],"tr":[10800,1640016850],"plf":[7200,3935],"kill":[3600,1640020450]}}

Anyone knows how to do this ? For example I need the Concorde from plane in a variable and the time values from gta in a variable. And some more from this string.

CodePudding user response:

So your first Part is okay and you rank you can just display like the first part as well

$AccData = json_decode($MobinfoString, true);

echo $AccData['playerinfo']['rank'].'<br/>';
echo $AccData['playerinfo']['cash'].'<br/>';
echo $AccData['playerinfo']['rank'].'<br/>';
echo $AccData['playerinfo']['plane'].'<br/>';

echo $AccData['character']['gta'][0].'<br/>';

but the character is on the same level as playerinfo so you need to access it from AccData. also gta is an array like health, so you have to specify which value you want to show, the first so 0 or second which is 1

  • Related