【问题标题】:Get Data from Array PHP从数组 PHP 中获取数据
【发布时间】:2013-06-20 17:59:17
【问题描述】:

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

【问题讨论】:

  • 你能发布你的json吗?
  • 每个项目的orderinfo 是一致的,还是有时是数组有时是JSON 字符串?
  • json在数组里面,但是还是没有说明为什么没有出现日期?
  • $item 是一个数组:$item['orderinfo']

标签: php arrays foreach


【解决方案1】:

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

$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'],
        ));

【讨论】:

    【解决方案2】:

    查看$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"}
    ]
    

    【讨论】:

    • 好吧,这是有道理的,但它仍然应该在列表项中显示日期,它目前只是显示为空白。
    【解决方案3】:

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

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

    【讨论】:

    • 是的,我想看看,只是一个项目符号列表
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 2016-06-30
    • 2018-08-16
    相关资源
    最近更新 更多