php json 数组
时间: 2023-11-16 11:27:18 浏览: 33
如何解析?
您可以使用 PHP 内置函数 json_decode() 来将 JSON 字符串转化为 PHP 数组或对象。例如:
$json_str = '{"name":"John Doe","age":30,"city":"New York"}';
$person = json_decode($json_str);
现在,$person 就是一个包含 JSON 数据的 PHP 对象,您可以使用 $person->name 或 $person->age 访问其中的成员。
相关问题
php解析json数组
在 PHP 中解析 JSON 数组可以使用内置的 json_decode() 函数。以下是一个示例代码:
```php
$json = '[{"name":"John","age":30},{"name":"Jane","age":25}]';
$array = json_decode($json, true);
foreach($array as $item) {
echo $item['name'] . ' is ' . $item['age'] . ' years old. ';
}
```
输出结果:
```
John is 30 years old. Jane is 25 years old.
```
在上面的示例中,首先定义了一个包含 JSON 字符串的变量 `$json`,然后使用 `json_decode()` 函数将其转换为 PHP 数组,并将其存储在 `$array` 变量中。第二个参数 `$assoc` 设置为 `true` 表示将 JSON 对象转换为 PHP 数组,而不是 PHP 对象。
最后,使用 `foreach` 循环遍历数组,并输出每个对象的属性值。
json数组转php数组
要将 JSON 数组转换为 PHP 数组,可以使用 PHP 的内置函数 json_decode()。例如:
```php
<?php
$jsonArray = '["apple", "banana", "orange"]';
$myArray = json_decode($jsonArray);
print_r($myArray);
?>
```
输出结果为:
```
Array
(
[0] => apple
[1] => banana
[2] => orange
)
```
在上面的示例中,我们使用了 json_decode() 函数将 JSON 数组 $jsonArray 转换成了 PHP 数组 $myArray。最后使用 print_r() 函数输出 $myArray。需要注意的是,json_decode() 函数默认将 JSON 数组转换为 PHP 关联数组,如果想要转换为 PHP 索引数组,可以将其第二个参数设置为 true。例如:
```php
<?php
$jsonArray = '["apple", "banana", "orange"]';
$myArray = json_decode($jsonArray, true);
print_r($myArray);
?>
```
输出结果同样为:
```
Array
(
[0] => apple
[1] => banana
[2] => orange
)
```
但是这里的 $myArray 是 PHP 索引数组。