doudao2954 2013-03-04 15:20
浏览 65
已采纳

使用单元格编号将PHP数组数据显示到表格单元格中

I have an array from database

Array
(
    [0] => stdClass Object
        (
            [cell] => 2
            [price] => 1543.65
        )

    [1] => stdClass Object
        (
            [cell] => 3
            [price] => 386.22
        )

)

and A table

<table>
    <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    <td>8</td>
    <td>9</td>
    <td>10</td>
    <td>12</td>
    <td>12</td>
    </tr>
    <tr>
    <?php
     print_r($sales);
     if(!empty($sales)) {
        foreach($sales as $sale) {

         if($sale->cell == 1) {echo "<td>".$sale->price."</td>";} else { echo "<td>0</td>"; }
         if($sale->cell == 2) {echo "<td>".$sale->price."</td>";} else { echo "<td>0</td>"; }
         ...
         if($sale->cell == 12) {echo "<td>".$sale->price."</td>";} else { echo "<td>0</td>"; }

        }

    } else {
    for($i=1; $i<=12; $i++) {
        echo "<td>0</td>";
    }
    }
    ?>
    </tr>
    </table>

I need to display price in same cell as it is in array. Now my problem is array size is not 12. Please help how can I display this on same cell as in array['cell']?

I want to display it as:

<tr>
    <td>0</td>
    <td>1543.65</td>
    <td>386.22</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
    </tr>

Your help and time is appreciated.

  • 写回答

3条回答 默认 最新

  • dou4064 2013-03-04 15:29
    关注

    I'm not sure I understand, completely, but this should do it:

    echo '<tr>';
    foreach($data as $value) {
        $array[$value->cell] = $value->price;
    }
    for($i = 0; $i <= 12; $i++) {
        echo '<td>';
        if(isset($array[$i])
            echo $array[$i];
        else echo '0';
        echo '</td>';
    }
    echo '</tr>';
    

    where $data is the array you got from the database and $array is the same data but converted into an associative array. This also assumes 12 columns, so it would be slightly more complex if the total number of columns needs to be flexible.

    edit: actually, I just noticed that your array's index doesn't match the 'cell' value. I fixed my code to reflect this, but if this is what your data looks like you should probably reevaluate your data structure.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题