-1

Please see json below

{
  "id": "1",
  "name": "john",
  "data": {
    "1": {
      "amount": "9000",
      "slip": "/image'/loidsds.jpg"
    },
    "method": "pump"
  }
}

I am trying to read amount and slip how can i manage to do this is PHP ?

I have tried the following

$object->data->1->amount and $object->data->1->slip

I got some errors please help me find an alternative

  • `$object->data->1->amount` and `$object->data->1->slip` maybe? What have you tried? Are you getting any kind of error? Sidenote; maybe `data` should be array, unless you explicitly need `1` as a key? – Tim Lewis Apr 25 '22 at 19:39
  • I have tried what you have suggested sadly it does not work. Please use an online editor you will observe the response. – Emanuel Paul Mnzava Apr 25 '22 at 19:54
  • Sorry, forgot the `{}` around the `1`. The more important part of my comment was asking you to show what you have already tried; don't ignore that in favour of pointing out an omission. Please [edit your question](https://stackoverflow.com/posts/72004851/edit) and provide more information. – Tim Lewis Apr 25 '22 at 19:57
  • Yes Tim {} solved my problem thank you very much – Emanuel Paul Mnzava Apr 26 '22 at 10:26

1 Answers1

2

Decode as an array by passing a truthy value as the second argument to json_decode():

$json = json_decode($string, true);
$amount = $json['data'][1]['amount'];
$slip = $json['data'][1]['slip'];

Or decode as an object, but then you have to brace the 1 because it's not normally a valid attribute name:

$json = json_decode($string);
$amount = $json->data->{1}->amount;
$slip = $json->data->{1}->slip;
Alex Howansky
  • 50,515
  • 8
  • 78
  • 98