如何使用php从json数据中正确获取id和标记名称和值
当我打印json数据时,我有下面的json内容如何使用php从json数据中正确获取id和标记名称和值,php,Php,当我打印json数据时,我有下面的json内容 Arweave\SDK\Support\Transaction Object ( [attributes:protected] => Array ( [id] => 101 [last_tx] => tx101 [owner] => tonyjohn [tags] => Array ( [0] => Array ( [name] => loco1 [value] => loco1_value )
Arweave\SDK\Support\Transaction Object ( [attributes:protected] => Array ( [id] => 101 [last_tx] => tx101
[owner] => tonyjohn [tags] => Array ( [0] => Array ( [name] => loco1 [value] => loco1_value )
[1] => Array ( [name] => loco2 [value] => loco2_tx_value ) ) [target] => 101
[quantity] => 10 [data] => product101 [reward] => 20532973 [end] => test_end ) )
现在,当我试图获取id的值,并用相应的值标记name
它抛出错误
json_decode() expects parameter 1 to be string
Invalid argument supplied for foreach()
这是代码
$file = 'product.json'
$data =file_get_contents($file);
print_r($data);
$json = json_decode($data, true);
// get id value
echo $id = $json['id'];
// loop and get tags name and values
foreach($json as $tags){
$tag_name = $tags['tags']['name'];
$tag_value =$tags['tags']['value'];
}
我认为您正在尝试使用类似对象的数组。打印$json变量,您将看到对象。如果您想访问id,请尝试:
echo $json->attributes['id'];
foreach的情况也一样
foreach($json->attributes['tags'] as $tag){}
第一个错误意味着
file\u get\u contents
没有返回字符串,因此它一定失败了。它可能找不到“product.json”。尝试file\u get\u内容(\uu DIR\uu.'/'.$file)代码>如果它与您的PHP脚本位于同一文件夹中。感谢您的帮助。*文件获取内容*工作正常。当我打印($data)时代码>。它转储我上面发布的json文件。只有当我尝试按照下面的代码获取id值和标记名称及值时,才会出现这些错误获取id值echo$id=$json['id'];//循环并获取每个($json as$tags){$tag_name=$tags['tags']['name'];$tag_value=$tags['tags']['value'];}
这没有多大意义。如果file\u get\u contents
起作用,那么它返回一个字符串,因此您得到的第一个错误是不符合逻辑的。echo gettype($data)
给了你什么?他正在使用json\u decode
,并将assoc
标志设为true,因此它应该返回一个数组。总之,根据他报告的错误,json\u encode
本身失败了。是的,我没有看到。好的,他可以在没有assoc标志的情况下尝试)