-4

I have a string that looks like this:

[
   {
      "id":"2",
      "price":"39.99",
      "timeStamp":"1506264307167",
      "quantity":"1",
      "colours":"Green",
      "pid":"234234234"
   },
   {
      "id":"2",
      "price":"39.99",
      "timeStamp":"1506264311757",
      "quantity":"1",
      "colours":"Blue",
      "pid":"234234234"
   }
]

I need to get the id from this JSON string using PHP.

So I tried this:

$details = '[
       {
          "id":"2",
          "price":"39.99",
          "timeStamp":"1506264307167",
          "quantity":"1",
          "colours":"Green",
          "pid":"234234234"
       },
       {
          "id":"2",
          "price":"39.99",
          "timeStamp":"1506264311757",
          "quantity":"1",
          "colours":"Blue",
          "pid":"234234234"
       }
    ]';

$details = json_encode($details, true);

$array = json_decode($details, true);
$oid = $array['id'];


echo $oid;

The code above is in a while loop so the echo $oid should echo the id multiple times.

anyway, the code above only prints this:

[
[

and when i look in the error log, i see this error:

PHP Warning:  Illegal string offset 'id'

Could someone please advice on this issue?

Thanks in advance.

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
David Hope
  • 1,426
  • 4
  • 21
  • 50

2 Answers2

2
<?php
$details = '[
       {
          "id":"2",
          "price":"39.99",
          "timeStamp":"1506264307167",
          "quantity":"1",
          "colours":"Green",
          "pid":"234234234"
       },
       {
          "id":"2",
          "price":"39.99",
          "timeStamp":"1506264311757",
          "quantity":"1",
          "colours":"Blue",
          "pid":"234234234"
       }
    ]';


$array = json_decode($details, true);

for($i=0;$i<count($array);$i++){
    $idValue = $array[$i]['id'];
    echo $idValue;
}

You need a loop to go through all the nested arrays and get all the ids.

pr1nc3
  • 8,108
  • 3
  • 23
  • 36
1

Try the following code:

<?php
$details = '[
       {
          "id":"2",
          "price":"39.99",
          "timeStamp":"1506264307167",
          "quantity":"1",
          "colours":"Green",
          "pid":"234234234"
       },
       {
          "id":"2",
          "price":"39.99",
          "timeStamp":"1506264311757",
          "quantity":"1",
          "colours":"Blue",
          "pid":"234234234"
       }
    ]';


$array = json_decode($details, true);
$oid = $array[0]['id'];


echo $oid;

Instead of encoding json string into json. Decode it to PHP array directly. And use [0] index to get first Json Object

mega6382
  • 9,211
  • 17
  • 48
  • 69