3

我不能完全从数组中获取数据,当我运行 foreach 循环时,它只显示 3 个列表项的空白列表。

当我打印我的数组时,它看起来像这样->

Array
(
    [1] => Array
        (
            [id] => 10
            [orderinfo] => Array
            [userid] => 210
            [date] => 2013-06-20 13:46:27
        )

    [2] => Array
        (
            [id] => 18
            [orderinfo] => helo
            [userid] => 210
            [date] => 2013-06-20 15:04:58
        )

    [3] => Array
        (
            [id] => 19
            [orderinfo] => {"order":[{"id":"2","name":"Basil Cress","qty":"1"},{"id":"4","name":"Sakura Mix","qty":"1"},{"id":"6","name":"Beetroot Shoots","qty":2},{"id":"28","name":"Celery","qty":2},{"id":"24","name":"Orange Capsicums","qty":"1"}]}
            [userid] => 210
            [date] => 2013-06-20 15:06:46
        )

)

到目前为止我的代码..

foreach ($orderdata as $item) {

    $orderinfo = json_decode($item->orderinfo, true);

    $orderitem[] = array(
        'date' => $item->date,
        'productname' => $orderinfo['name'],
        'productqty' => $orderinfo['qty'],
    );              
}


echo "<pre>";
print_r($orderdata);
echo "</pre>";
?>



<?php foreach ($orderitem as $orderitems) {   ?>
  <li> 
    <?php echo  $orderitems['date']; ?>
  </li>
<?php }; ?>
4

3 回答 3

2

尝试像这样在循环之前声明您的数组。你已经在这样做了吗?

$orderitem = array();
foreach ($orderdata as $item) {

    $orderinfo = json_decode($item->orderinfo, true);

    $orderitem[] = array(
        'date' => $item->date,
        'productname' => $orderinfo['name'],
        'productqty' => $orderinfo['qty'],
    );              
}

您还可以尝试以不同方式填充数组,如下所示:

array_push($orderitem,array(
            'date' => $item->date,
            'productname' => $orderinfo['name'],
            'productqty' => $orderinfo['qty'],
        ));
于 2013-06-20T18:23:11.067 回答
1

查看 JSON 的结构$orderInfo。它是一个嵌套数组。所以$orderInfo['name']不存在。您希望$orderInfo[0]['name']或其他一些数字索引来填充数据。

这是一个对象数组,它被解码为关联数组的数组。你需要再往下走一层才能得到这个名字。

[
    {"id":"2","name":"Basil Cress","qty":"1"},
    {"id":"4","name":"Sakura Mix","qty":"1"},
    {"id":"6","name":"Beetroot Shoots","qty":2},
    {"id":"28","name":"Celery","qty":2},
    {"id":"24","name":"Orange Capsicums","qty":"1"}
]
于 2013-06-20T18:03:37.530 回答
1

可能只是你的CSS吗?背景颜色与文本颜色相同?我知道这很愚蠢,但谁知道...

试试 print_r($orderitem); 就像你对 $orderdata 所做的那样

于 2013-06-20T18:09:54.673 回答