elize elize - 5 months ago 19
JSON Question

php convert Array to json and then parsing json

I want convert an array to json

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>


Result:

{"a":1,"b":2,"c":3,"d":4,"e":5}


Now I want call value of 'a'.

$value = {"a":1,"b":2,"c":3,"d":4,"e":5}
echo $value->a;


It no print anything.

So I try convert it to object:

<?php
$value = {"a":1,"b":2,"c":3,"d":4,"e":5};
$value = json_encode($arr);
$value = json_decode($arr);
echo $value->a;

?>


It no print anything too.

can please tell me my mistake?

Answer

Try the following solution:

<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
$json = json_encode($arr);
$json = json_decode($json);
echo $json->a;
?>

Demo: http://ideone.com/MkWWdA