PHP访问多维关联数组
以下是我编写的代码块:PHP访问多维关联数组,php,arrays,json,associative-array,Php,Arrays,Json,Associative Array,以下是我编写的代码块: $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, C
$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",
}
]
}
我想知道和需要知道的是如何获取或访问每个元素的值,即价格
和产地名称
。我尝试用$result[0]['price']['origin\u 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 ...
让我们从乞讨中假设:
$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字符串表示对象,而不是数组
注:
您向我们展示的JSON字符串格式错误,不应在JSONString对象的最后一个属性末尾添加逗号
有时返回的结果在使用前需要修复。可以使用来修复无效的JSON。将修正后的JSON解码为PHP关联数组后,可以使用提取price数组,然后使用获取price和origin name信息,如下所示:
<?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";
}
});
发布您的整个代码返回的数据是否为JSON字符串?除了JSON是InValid@RiggsFolly我重写代码。因此,基本上我使用curl从提供的linkapi获取所有数据,因此json结果结构是由某人编写的else@mickmackusa它需要重写才能重新打开,但既然这里已经有了答案,重写这个问题就可以解决整个问题。因此,如果这真的是需要回答的问题,应该发布一个新的问题。您测试了该代码吗?@RiggsFolly抱歉,我更新了答案,然后您需要告诉OP,只有当他们获得数据源修复JSON字符串时,该代码才会起作用producer@RiggsFolly是的,谢谢,我在第二次更新中做了:)Kudo感谢Benoit给出了正确的答案。很显然,我从这个新的结构化json格式中学到了一些东西,需要先对其进行解码。实际上,如果你检查一下他下面的注释,他不会这么做question@RiggsFolly感谢您的反馈;适当地注意到并修改了我的答复。