这些是我写的代码块:
$url = "http://links";
$curl_post_data = array(
"username" => "guest",
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_PORT, 8889);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
$curl_response = curl_exec($curl);
curl_close($curl);
$result = $curl_response;
echo $result
我尝试的是回显$ result变量并返回如下:
{
"price": [
{
"price": "2000",
"origin_name": "JPN",
},
{
"price": "5000",
"origin_name": "USA",
}
]
}
我想要和需要知道的是如何获取或访问price
和origin_name
的每个元素的值。我尝试使用$result[0]['price']['origin_name'][0]
进行调用,但它不起作用并返回如下:
Warning: Illegal string offset 'price' in .... on line ...
Warning: Illegal string offset 'origin_name' in .... on line ...
{
我也尝试使用foreach
函数编写,如下所示:
foreach($result['price'] as $res){
echo $res[0];
}
但是它返回了相同的错误消息:
Warning: Illegal string offset 'price' in .... on line ...
Warning: Invalid argument supplied for foreach() in .... on line ...
答案 0 :(得分:2)
让我们假设从开始:
$result = '{
"price": [
{
"price": "2000",
"origin_name": "JPN"
},
{
"price": "5000",
"origin_name": "USA"
}
]
}';
$resultDecoded = json_decode($result, true);
foreach ($resultDecoded["price"] as $item) {
echo $item["price"];
}
问题是JSON String表示一个对象,而不是一个数组
注:
您向我们展示的JSON字符串格式不正确,不应在JSONString对象的最后一个属性的末尾添加逗号。
答案 1 :(得分:0)
有时在使用之前需要修复的结果需要修复。可以使用preg_replace()来修复无效的JSON。将经过修复的JSON解码为PHP关联数组后,可以使用array_pop()提取价格数组,然后使用array_walk_recursive()获取价格和原始名称信息,如下所示:
<?php
// take badly formatted JSON ...
$result = '{
"price": [
{
"price": "2000",
"origin_name": "JPN",
},
{
"price": "5000",
"origin_name": "USA",
}
]
}';
// ... and remove the superfluous commas:
$pat = "/(o.+),/";
$replace = "$1";
$nu_result = preg_replace($pat,$replace,$result);
// now convert JSON into PHP array and traverse it
$resultDecoded = json_decode($nu_result, true);
$arr = array_pop($resultDecoded);
array_walk_recursive($arr,function($e,$i) {
if ($i == "price") {
echo "price: ",$e,"\n";
}
else
if ($i == "origin_name") {
echo "origin_name: ",$e,"\n\n";
}
});
请参阅live code