Markdown

[PHP] how to convert a json to a php object in symfony

https://stackoverflow.com/questions/7360417/how-to-convert-a-json-to-a-php-object-in-symfony2

```
$j = json_decode('{"indices":[1,2,6]}');

var_dump($j);
leads to:
object(stdClass)#1 (1) {
  ["indices"]=>
  array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(6)
  }
}
...

{#161 ▼
  +"indices": array:3 [
    0 => 1
    1 => 2
    2 => 6
  ]
}
type: string $content:

先將 json 解開 並加上參數 true 轉成 array

$j = json_decode('{"indices":[1,2,6]}', true);~

再從array取得元素

 dump($j['indices'][0]);

1


---------------------------------------------------------------------------

回到上一篇的code驗證看看:

```
        $data = json_decode($content, true);~

         $u = $data['userName'];~
         $m = $data['msg'];~

    //   $j = json_decode('{"indices":[1,2,6]}', true);~

         $response->setContent(
             "content-type: " . gettype($content) . "   \$content: " .$content . " userName  " . $u
          );~
```
content-type: string   $content: {"userName":"test","msg":"test"} userName  test

成功了~



留言