0

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?

elize
  • 435
  • 1
  • 8
  • 19
  • 3
    In your last code snipped, you already have a json string - you don't have to json_encode it again - just decoding is enough. You Just have to put single quotes around it (the json string). – nimmneun Jun 12 '16 at 14:23
  • 2
    use error_reporting. `$value = {...}` is a syntax error... (It is a valid Javascript object, but you are in php) – Zimmi Jun 12 '16 at 14:23

1 Answers1

1

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

Sebastian Brosch
  • 42,106
  • 15
  • 72
  • 87