要让PHP返回一个对象数组,你可以使用json_encode()
函数将对象数组转换为JSON格式,然后使用json_decode()
函数将JSON格式转换回对象数组。
下面是一个例子:
// 创建一个对象数组
$users = [
(object) ['name' => 'John', 'age' => 25],
(object) ['name' => 'Jane', 'age' => 30],
(object) ['name' => 'Bob', 'age' => 35]
];
// 将对象数组转换为JSON格式
$json = json_encode($users);
// 将JSON格式转换回对象数组
$decodedUsers = json_decode($json);
// 打印对象数组
print_r($decodedUsers);
这将输出:
Array
(
[0] => stdClass Object
(
[name] => John
[age] => 25
)
[1] => stdClass Object
(
[name] => Jane
[age] => 30
)
[2] => stdClass Object
(
[name] => Bob
[age] => 35
)
)
注意:json_decode()
函数默认将JSON对象转换为PHP关联数组,如果要将其转换为对象数组,可以将json_decode()
函数的第二个参数设置为true
,如下所示:
$decodedUsers = json_decode($json, true);
上一篇:某个值是否在数组值区间php
下一篇:php改数组键名
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站