1

i have below json code

 {"1":1,"5":1}

when i decode the above json i got object array using the below php statement.

$array_val = (array)json_decode($price);

i got a below array.

Array
(
  [1] => 1
  [5] => 1
)

but the below statement does not work

echo $array_val[1];

the below error occurred.
Undefined offset: 1

How to resolve this issue?

3 Answers 3

7

try this DEMO

PHP

$json = '{"1":1,"5":1}';
$array_val=json_decode($price, true);
echo $array_val[1];

OUTPUT :

1
0
4

Note that json_decode($string) returns an object, not an array (which is why your code doesn't behave).

To return an array instead, use:

$arr = json_decode($string, true);

See also http://php.net/manual/en/function.json-decode.php

3

You can get this using below code

$array_val=json_decode($price);
echo $array_val->{1}

OR

$array_val=json_decode($price,true);
echo $array_val[1]

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.