【问题标题】:Display value of two-dimensional php array in table在表格中显示二维php数组的值
【发布时间】:2014-09-25 14:53:20
【问题描述】:

我从 MySQL 中提取了一个名为“$agents”的数组,如下所示:

Array (
  [0] => Array ( [agent] => Agent/1002 [total] => 02:11:07 )
  [1] => Array ( [agent] => Agent/1400 [total] => 01:49:53 )
  [2] => Array ( [agent] => Agent/1500 [total] => 03:26:29 ) )

然后另一个 MySQL 查询创建一个表为:

while ($row = mysql_fetch_row($q)) {
    $result .="<tr><td>".$row[0]."</td><td align=center>".
      $row[1]."</td><td align=center>".
      $row[2]."</td><td align=center>".
      $row[3]."</td><td align=center>".$agents['0']['total']."</tr>";
}

如何从表格最后一列中显示的数组中获取“总计”值? 我想插入每个代理的总数。使用 if 语句,非常简化,例如:

if $row[0] == $agents['0']['agent'] echo $agents['0']['total'] else echo 'NONE'" 

尝试使用“foreach”循环,但无法正常工作。 关于如何做到这一点的任何想法/建议?

【问题讨论】:

    标签: php mysql arrays multidimensional-array


    【解决方案1】:

    您可以在第二次提取之上初始化一个计数器。像这样:

    $agents = holds your first data fetches from db
    
    $i = 0; // initialize a counter
    while ($row = mysql_fetch_row($q)) {
    
        // condition block
        if($row[0] == $agents[$i]['agent']) {
            $total = $agents[$i]['total']; // if they match, assign the total
        } else {
            $total = ''; // else just assign an empty string
        }
    
        $result .="
            <tr><td>".$row[0]."</td>
            <td align=center>".$row[1]."</td>
            <td align=center>".$row[2]."</td><td align=center>".$row[3]."</td>
            <td align=center>".$total."</tr>
        ";
        $i++; // increment
    }
    

    【讨论】:

    • 刚刚试了一下,我想差不多了。将 if($row[0] == $agents[$i]['total']) 更改为 if($row[0] == $agents[$i]['agent'])。它仅填充第一个结果的总数,其他 3 行的“总计”列为空结果。
    • 通过此更正它可以工作,但仅适用于第一行。可能与计数器没有增加有关吗?
    • @Jompie 很高兴这有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-02
    • 2021-08-17
    • 2015-10-25
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    相关资源
    最近更新 更多