1

I have a JSON data in the following format:

{
   "pr":"1",
   "0":{
      "pr":"2",
      "rfq":"2"
   },
   "1":{
      "pr":"3",
      "rfq":"3"
   }
}

I try to decode this JSON and when I access the first data like that:

$decode = json_decode( array(myjsondatas));
echo $decode->pr;

it prints 1.

But when I try to access array 0 and 1 by using this syntax $decode->[0]->pr;, it gives me an error:

Parse error: syntax error, unexpected '[', expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'

How can I access the data from array 0 and 1?

PS: This is how I did to build my json data 'myjsondatas' is not a variable

$arr = array("pr" => '2' ,  "rfq" => '2');
$arr1 = array("pr" => '3' ,  "rfq" => '3');

$json = json_encode(array("pr" => '1', $arr, $arr1));
  • 1
    that array is too much: `array(myjsondatas)`. make it `$decode = json_decode($myjsondatas);` – Jeff Sep 13 '18 at 13:45
  • I suppose the missing `$` in front of `myjsondatas` is just a typo here.. – Jeff Sep 13 '18 at 13:46
  • sorry, im trying to express my json datas as a word. – Dianne Amparo Sep 13 '18 at 13:49
  • after removing the array (my first comment), then the correct syntax is `echo $decoded->{'0'}->pr;` – Jeff Sep 13 '18 at 13:52
  • Use `$decode = json_decode( $myjsondatas , TRUE );` – Michel Sep 13 '18 at 13:53
  • _after your edit_: so, jsondatas is not even a json but a simple array? Why json_decode it then?? – Jeff Sep 13 '18 at 13:53
  • forget the json_decode, simply do a `$fullarray = array("pr" => '1', $arr, $arr1);` and then `echo $fullarray[0]['pr'];` – Jeff Sep 13 '18 at 13:55
  • usefull read: [What is JSON and why would I use it?](https://stackoverflow.com/questions/383692/what-is-json-and-why-would-i-use-it) – Jeff Sep 13 '18 at 13:56
  • 1
    Anyways I did your syntax @Jeff. Everything seems working. To all of you guys thank you for your patience teaching me. – Dianne Amparo Sep 13 '18 at 13:58

1 Answers1

0

the index is "0", not 0

You can use a variable to store the index as below :

$myjsondata = '{
    "pr":"1",
    "0":{
        "pr":"2",
        "rfq":"2"
    },
    "1":{
        "pr":"3",
        "rfq":"3"
    }
}';

$decode = json_decode($myjsondata);

$someIndex = "0";

var_dump($decode->$someIndex);

echo "myjsondata->0->pr gives : " . $decode->$someIndex->pr;

Output :

object(stdClass)[2]

public 'pr' => string '2' (length=1)

public 'rfq' => string '2' (length=1)

myjsondata->0->pr gives : 2

Cid
  • 14,968
  • 4
  • 30
  • 45