php json字符串转数组
时间: 2023-07-01 21:25:26 浏览: 50
在 PHP 中,可以使用 `json_decode()` 函数将 JSON 字符串转换为数组。该函数的语法如下:
```php
mixed json_decode ( string $json [, bool $assoc = FALSE [, int $depth = 512 [, int $options = 0 ]]] )
```
参数说明:
- `$json`:必须,要解码的 JSON 字符串。
- `$assoc`:可选,当该参数为 true 时,将返回数组;为 false 时,将返回对象。默认为 false。
- `$depth`:可选,设置递归深度,如果超过了这个深度将抛出异常。默认为 512。
- `$options`:可选,用于控制 JSON 解码过程的选项。默认为 0。
使用示例:
```php
$json_str = '[{"name":"John","age":30,"city":"New York"},{"name":"Mike","age":25,"city":"Chicago"}]';
$arr = json_decode($json_str, true);
print_r($arr);
```
输出结果:
```
Array
(
[0] => Array
(
[name] => John
[age] => 30
[city] => New York
)
[1] => Array
(
[name] => Mike
[age] => 25
[city] => Chicago
)
)
```
在这个示例中,我们将一个 JSON 字符串转换为了一个数组,并使用 `print_r()` 函数打印了数组的内容。