猿问

使用 php 将 Json 数据解码并打印到 html 表中

我有以下编码的json数组:


function getMostActive($link) {

    $query = "SELECT username AS staff, COUNT(*) As Total FROM vloer_action_logs WHERE task_type = 'job_status_change' AND accessed_time >= '2019-12-31' AND accessed_time <= '2020-01-06'

Group by username ORDER BY 2 DESC";

    $result = mysqli_query($link, $query);

    if (!$result)

        die(mysqli_error($link));


    $jsonData = array();

    while ($array = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

        $jsonData[] = $array;

    }

    return json_encode($jsonData);

}

我想在表格中打印此数据。已尝试以下方法


$getMostActive = json_decode(getMostActive($link),true);

<?php foreach ($getMostActive as $key=>$value) { ?>

    <tr>

     <td class="dark"><?php echo $value['Floor'];?> </td>

     <td class="end"><?php echo $value['Total'];?></td>

    </tr>

但它扔给我的错误:


尝试在 /var/www/html/用户/报告/报告/报告中获取非对象的属性“楼层.php


我怎么能解决这个问题。提前致谢


三国纷争
浏览 155回答 3
3回答

慕神8447489

正如许多人已经说过的那样,您在 getMostActive() 函数的第一行中的查询不会选择任何名为“楼层”的字段。因此,在解码 json 的那一刻,您将获得一个类似于以下内容的数组:[&nbsp; [&nbsp; &nbsp; "staff" => "name1",&nbsp; &nbsp; "Total" => 5&nbsp; ],&nbsp; [&nbsp; &nbsp; "staff" => "name2",&nbsp; &nbsp; "Total" => 3&nbsp; ]&nbsp; // [...]]没有一个条目表示包含您要查找的“楼层”字段的单个行。若要进行检查,请将以下代码暂时放在表的正前方echo '<pre>';var_dump($getMostActive);,然后修复查询。就我所看到的,其他一切都是正确的。希望我能帮上什么忙。

慕森王

你有几个错误。首先,您尝试解码的 JSON 必须是字符串。而且您在解码时也缺少$。以下是工作代码:<?php&nbsp;$getMostActive = '[{"Floor":"carpet","Total":"22"},{"Floor":"ceramic-tiles","Total":"13"},{"Floor":"hardwood","Total":"13"}]';$getMostActive = json_decode($getMostActive,true);?><table><?phpforeach ($getMostActive as $key=>$value) {&nbsp;?>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp;<td class="dark"><?php echo $value['Floor'];?> </td>&nbsp; &nbsp; &nbsp;<td class="end"><?php echo $value['Total'];?></td>&nbsp; &nbsp; </tr><?php&nbsp;}?></table>

慕村9548890

试试下面一个。&nbsp; &nbsp; $getMostActive = '[{"Floor":"carpet","Total":"22"},{"Floor":"ceramic-tiles","Total":"13"},{"Floor":"hardwood","Total":"13"}]';$getMostActive = json_decode($getMostActive,true);&nbsp;foreach ($getMostActive as $key=>$value) { ?>&nbsp; &nbsp; <tr>&nbsp; &nbsp; &nbsp;<td class="dark"><?php echo $value['Floor'];?> </td>&nbsp; &nbsp; &nbsp;<td class="end"><?php echo $value['Total'];?></td>&nbsp; &nbsp; </tr>&nbsp;<?php } ?>看起来您的 JSON 数据不正确,请检查 .single quote
随时随地看视频慕课网APP
我要回答