从Array PHP获取数据

时间:2013-06-20 17:59:18

标签: php arrays foreach

我无法从数组中获取数据,只是在运行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 }; ?>

3 个答案:

答案 0 :(得分: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'],
        ));

答案 1 :(得分:1)

查看$orderInfo的JSON结构。它是一个嵌套数组。所以$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"}
]

答案 2 :(得分:1)

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

尝试print_r($ orderitem);就像你使用$ orderdata

一样