douxi3085 2016-10-13 03:35
浏览 76

PHP和AngularJS关联数组循环

So I have a simple html file and this is the output:

enter image description here

The html file code:

<tr ng-repeat="(key, value) in items">
  <td ng-bind="key"></td>
  <td ng-bind="value"></td>
</tr>

Angular file

$scope.viewCart = function() {
  $('#cartModal').openModal();
  $http.get('../crud/cartCRUD/cart-data.php')
  .success(function(data) {
  $scope.items = data;
  })
}

cart-data.php

print json_encode($_SESSION['cart_items']);

My $_SESSION['cart-items'] is an associative array containing of key(product id) => value (quantity)

If you access the php file directly using print_r($_SESSION['cart-items']), you will get this:

Array
(
    [35] => 23
    [10] => 7
)

Meaning, the output from my html file is correct.

Now what I wanted to do is instead of showing the key and value in my ng-repeat, I want to get the product name from mysql database using the session array key(product id).

For now this is what I did

$statement = $conn->query("SELECT * FROM product WHERE id IN (".implode(',',array_keys($_SESSION['cart_items'])).")");

while($row = $statement->fetch()) {
    $data[] = $row;
}

print json_encode($data);

and in the html file:

  <table>
     <thead>
        <tr>
           <th>Name</th>
           <th>Price</th>
           <th>Quantity</th>           
        </tr>
     </thead>
     <tbody>
        <tr ng-repeat="item in items">
           <td ng-bind="item.name"></td>
           <td ng-bind="item.price"></td>
           <td>HOW TO OUTPUT THE QUANTITY</td>
        </tr>
     </tbody>
  </table>

This works though the problem is I cannot get the value of the key pair (quantity) anymore. Is there a proper way on doing this?

  • 写回答

1条回答 默认 最新

  • dongya1875 2016-10-13 03:44
    关注

    Inside de while statement you can use

    $row["quantity"] = $_SESSION["cart-items"][$row["id"]];
    
    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突