簡體   English   中英

從JSON數組創建HTML表

[英]Create HTML table from JSON array

我已經嘗試了幾個小時,用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以進行格式化。

$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上設置foreach循環

或者,您可以向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>

Trying to get property of non-object意味着->property調用之一失敗,因為該屬性不存在。 在這種情況下,$ o-> result失敗了。

如果打印出$ 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>
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM