0

I'm trying to decode API to PHP.

API EXM

{
"users":[
          {"user":"john",
          "user1":"Tabby",
          "user2":"Ruby",
          "user3":"Silver"}
]
}

tilte users = 0 (It's empty)

I tried with this code but it's not working (blank page)

<?php
$json = '{ "users"[ {"user":"john", "user1":"Tabby", "user2":"Ruby", "user3":"Silver"}';

$arr = json_decode($json);

echo $arr->users->{0}->user; //blank page
echo $arr->users->user1; //blank page
echo $arr->users->0->user2; //syntax error, unexpected '0' (T_LNUMBER), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in
?>
stackr
  • 31
  • 4

2 Answers2

1

$arr->users is an array and not an object. So if you change your script to

<?php
$json = '{
"users":[
    {"user":"john",
    "user1":"Tabby",
    "user2":"Ruby",
    "user3":"Silver"}
]
}';

$arr = json_decode($json);
print_r($arr);

echo $arr->users[0]->user,"\n";
echo $arr->users[0]->user1,"\n";
echo $arr->users[0]->user2,"\n";
?>

... the output is ...

stdClass Object
(
    [users] => Array
        (
            [0] => stdClass Object
                (
                    [user] => john
                    [user1] => Tabby
                    [user2] => Ruby
                    [user3] => Silver
                )

        )

)
john
Tabby
Ruby
Wiimm
  • 2,971
  • 1
  • 15
  • 25
  • What if looks like this ? {"address":[{ "AL": "Alabama", "AK": "Alaska", "AS": "American Samoa", "AZ": "Arizona", "AR": "Arkansas", "details":{ "1":{ "total":{ "id1":"140.0", "id2":"140.0" }}} }]} PHP Fatal error: Cannot use object of type stdClass as array – stackr Feb 02 '21 at 22:43
  • @stackr: My PHP decodes your json sting very well (without error). – Wiimm Feb 02 '21 at 23:06
  • yes it's working with first example but its not working with this one ( more levels), {"address":[{ "AL": "Alabama", "AK": "Alaska", "AS": "American Samoa", "AZ": "Arizona", "AR": "Arkansas", "details":{ "1":{ "total":{ "id1":"140.0", "id2":"140.0" }}}}]} – stackr Feb 02 '21 at 23:35
  • I have no issues with the second string. I did: `$j = ' ... '; $a = json_decode($j); print_r($a);` – Wiimm Feb 05 '21 at 12:13
0
<?php
  $json = '{
  "users":[
      {"user":"john",
      "user1":"Tabby",
      "user2":"Ruby",
      "user3":"Silver"}
   ]
 }';
$json = str_replace(array('[',']'),'',$json);
$arr = json_decode($json,true);
print_r($arr);
?>
valex
  • 11
  • 1