我一直在努力创建一个包含JSON数组数据的简单表。
以下是一个例子。我不知道为什么这段代码不起作用。错误是:
“试图获取非对象的属性”。
$json_string = file_get_contents("https://bittrex.com/api/v1/public/getmarkethistory?market=BTC-HYPER&count=5");
$array = json_decode($json_string);
?>
<table><tr><th>
<?php foreach($array as $o): ?>
<tr>
<td><?php $o->result->TimeStamp ?></td>
</tr>
<?php endforeach; ?>
</table>
请查看用于格式化的json_string的URL。
答案 0 :(得分:0)
$json_string = file_get_contents("https://bittrex.com/api/v1/public/getmarkethistory?market=BTC-HYPER&count=5");
$array = json_decode($json_string);
?>
<table>
<?php foreach($array->result as $o)
{
echo "<tr>
<td>".$o->TimeStamp."</td>
</tr>";
} ?>
</table>
这应该有效。您必须在$array->result
答案 1 :(得分:0)
或者,您可以向json_decode($json_string, true)
添加第二个参数,使其成为数组而不是对象。考虑这个例子:
<?php
$json_string = file_get_contents("https://bittrex.com/api/v1/public/getmarkethistory?market=BTC-HYPER&count=5");
$array = json_decode($json_string, true);
?>
<table border="1" cellpadding="10">
<thead><tr><th>Timestamp</th></tr></thead>
<tbody>
<?php foreach($array['result'] as $key => $value): ?>
<tr>
<td><?php echo $value['TimeStamp']; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
答案 2 :(得分:0)
Trying to get property of non-object
表示其中一个->property
调用失败,因为该属性不存在。在这种情况下,它失败了$ o-&gt;结果。
如果您打印出$ array的内容,您可以看到它的结构如下:
print_r($array);
输出:
stdClass Object
(
[success] => 1
[message] =>
[result] => Array
(
[0] => stdClass Object
(
[Id] => 10044
[TimeStamp] => 2014-06-12T04:36:32.227
[Quantity] => 3
[Price] => 2.9E-5
[Total] => 8.7E-5
[FillType] => FILL
[OrderType] => BUY
)
[1] => stdClass Object
(
[Id] => 10040
[TimeStamp] => 2014-06-12T04:23:22.683
[Quantity] => 49.9
[Price] => 2.5E-5
[Total] => 0.0012475
[FillType] => PARTIAL_FILL
[OrderType] => SELL
)
...
现在您可以按照此结构来获取内部对象:
<?php
$json_string = file_get_contents("https://bittrex.com/api/v1/public/getmarkethistory?market=BTC-HYPER&count=5");
echo "<table>\n";
$array = json_decode($json_string);
foreach ($array->result as $o) {
echo "<tr><td>$o->TimeStamp</td></tr>\n";
}
echo "</table>\n";
输出:
<table>
<tr><td>2014-06-12T04:36:32.227</td></tr>
<tr><td>2014-06-12T04:23:22.683</td></tr>
<tr><td>2014-06-12T04:01:43.217</td></tr>
<tr><td>2014-06-12T02:02:29.03</td></tr>
...