在php页面上循环访问数据库中的json数据

时间:2015-08-26 12:56:23

标签: php mysql json

我在数据库表中有这个列:

value=[
       {"srno":1,
        "name":"Gaspari Aminolast ",
        "quantity":"2",
        "price":"2920.0000",
        "total_bill":5840
       },
       {"srno":2,
        "name":"Gaspari Amino Max ",
         "quantity":"2",
         "price":"2640.0000",
         "total_bill":5280
       },
       {"srno":3,
        "name":"Myofusion 10Lbs",
        "quantity":"2",
        "price":"8400.0000",
        "total_bill":16800}
]

我的PHP代码是:

<?php
    $getbill="select value from $tbl where bill_id='$_GET[id]' ";
    $result=mysql_query($getbill)or die(mysql_error());
    $results = array();
    while($row=mysql_fetch_array($result))
    {
         $results[] = json_decode($row['value']);
    }
    print_r($results);
    foreach($results as $key=>$value){
?>
<tbody>
    <tr>
        <td><?php echo $value['srno'];?></td>
        <td><?php echo $value['name'];?></td>
        <td><?php echo $value['quantity'];?></td>
        <td><?php echo $value['price'];?></td>
        <td ><?php echo $value['total_bill'];?></td>
    </tr>
</tbody>
<?PHP   
    }
?>

我对如何循环浏览并打印所有内容感到困惑。

print_r():

Array ( 
      [0] => Array ( 
         [0] => stdClass Object ( 
                       [srno] => 1 
                       [name] => Gaspari Aminolast 
                       [quantity] => 2 
                       [price] => 2920.0000 
                       [total_bill] => 5840 
                  ) 
          [1] => stdClass Object ( 
                       [srno] => 2 
                       [name] => Gaspari Amino Max 
                       [quantity] => 2 
                       [price] => 2640.0000 
                       [total_bill] => 5280 
                  ) 
          [2] => stdClass Object ( 
                       [srno] => 3 
                       [name] => Myofusion 10Lbs 
                       [quantity] => 2 
                       [price] => 8400.0000 
                       [total_bill] => 16800 
                   ) 
       )
)

1 个答案:

答案 0 :(得分:0)

如果您注意到,现在我重新格式化了值列,每个值列都包含一个表示对象数组的JSON字符串。

因此,对于存储在value数组中的每个$results,您需要执行另一个循环来检查对象的内部数组。像这样:

<?php
    $getbill="select value from $tbl where bill_id='{$_GET[id]}' ";
    $result=mysql_query($getbill)or die(mysql_error());
    $results = array();
    while($row=mysql_fetch_array($result))
    {
         $results[] = json_decode($row['value']);
    }
    print_r($results);

    echo '<tbody>';

    foreach($results as $value) :
        foreach( $value as $object) :
?>
    <tr>
        <td><?php echo $object->srno;?></td>
        <td><?php echo $object->name;?></td>
        <td><?php echo $object->quantity;?></td>
        <td><?php echo $object->price;?></td>
        <td><?php echo $object->total_bill;?></td>
    </tr>

<?php   
        endforeach;
    endforeach;
?>
</tbody>

我还将<tbody></tbody>移到了循环之外,因为这也会导致您的布局出现问题。