为什么我无法用PHP从json文件中获取值? 我得到零值?已经试了几个小时。
<?php
$json_string = 'http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=44';
$jsondata = file_get_contents($json_string);
$data = json_decode($jsondata, TRUE);
print_r($data);
echo "<br><br><br><br>";
foreach ($data as $recenttrades) {
echo "VALUES('{$recenttrades->quantity}', '{$recenttrades->price}' ";
}
?>
更新:但无法从primaryname和primarycode获取值。
我试过这个:
$json_string = 'http://pubapi.cryptsy.com/api.php?method=marketdatav2';
$jsondata = file_get_contents($json_string);
$data = json_decode($jsondata, TRUE);
//print_r($data);
foreach ($data["market"] as $markets) {
echo "Primary code: <strong>{$markets['primarycode']}</strong><br>";
foreach($markets as $market) {
foreach($market as $attributes) {
foreach($attributes["recenttrades"] as $recenttrade) {
echo "quantity: " . $recenttrade['quantity'] .", price: " . $recenttrade['price'] . "<br>";
}
}
}
}
答案 0 :(得分:2)
recenttrades
嵌套在该数组中。尝试
foreach ($data['return']['markets']['FST']['recenttrades'] as $recenttrades) {
答案 1 :(得分:2)
recenttrades
是嵌套的几个级别,因此仅仅执行foreach($data as $recenttrades)
是不够的。
你需要这样做:
$recentTrades = $data['return']['markets']['FST']['recenttrades'];
foreach($recentTrades as $recentTrade) {
...
}
答案 2 :(得分:2)
其他人提到你正在处理嵌套数组,而不是对象。除了指出嵌套相当深的问题之外,我建议用foreach
进行挖掘(我可能会被钉在十字架上):
<?php
$json_string = 'http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=44';
$jsondata = file_get_contents($json_string);
$data = json_decode($jsondata, TRUE);
//print_r($data);
echo "<br><br><br><br>";
foreach ($data as $markets) {
foreach($markets as $market) {
foreach($market as $attributes) {
foreach($attributes["recenttrades"] as $recenttrade) {
//echo "<pre>";
//print_r($recenttrade);
//echo "</pre>";
echo "VALUES('{quantity: " . $recenttrade['quantity'] ."}', 'price: {" . $recenttrade['price'] . "}')";
}
}
}
}
&GT;
这将确保您获取此阵列级别的每个recentrades
项目。通过这种方式,您可以将其他市场添加到API中,并且您的代码不会仅锁定在名为&#34; FST&#34;的项目中。
答案 3 :(得分:1)
recenttrades
深深嵌套,你要求数组,而不是对象。这似乎有效:
foreach ($data['return']['markets']['FST']['recenttrades'] as $recenttrades) {
echo "VALUES('{$recenttrades['quantity']}', '{$recenttrades['price']}' ";
}
答案 4 :(得分:0)
为了响应您的更新,您希望在市场上进行循环,请尝试以下操作:
foreach ($data['return']['markets'] as $market) {
echo "Primary code: <strong>{$market['primarycode']}</strong><br>";
foreach ($market["recenttrades"] as $recenttrade) {
echo "quantity: " . $recenttrade['quantity'] .", price: " . $recenttrade['price'] . "<br>";
}
}