[英]How can i modify my PHP script to read an API as an array?
我在 Wordpress 中有一个 PHP 脚本,如果它是一个数组,它会处理 API 数据,但我有一个解决办法。 这是我的 PHP 脚本:
$results = wp_remote_retrieve_body( wp_remote_get('https://...') );
$results = json_decode( $results );
if( ! is_array( $results ) || empty( $results ) ){
return false;
}
这是 API 的样子。 它不是一个数组,所以我如何修改上面的脚本来支持它?:
{
"msg": "OK",
"server_time": "2021-03-04 01:42:20",
"status": 200,
"result": {
"total_pages": 2,
"files": [
{
"Country": "USA",
"city": "NYC",
"zip: "12345",
},
{
"Country": "RUSSIA",
"city": "MOSCOW",
"zip: "12345",
},
json_decode()
的可选第二个参数指示您是否想要返回 object 或数组。 您当前获得的是 object。 要获取一个数组,请传递一个真实值:
$results = json_decode($results, true);
json_decode 接受第二个参数,当设置为 true 时,返回 JSON object 一个关联数组。 因此,为了处理收到的数据,按照您的要求,您需要添加 true,否则默认情况下 JSON object 将返回为 object。
$results = json_decode( $results, true );
有关详细信息,请参阅以下文档:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.