2013-06-20 175 views
3

我無法完全從數組中獲取數據,當我運行我的foreach循環時,它只顯示了3個列表項的空白列表。從數組中獲取數據PHP

當我打印我的陣列,它看起來像這樣 - >

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 }; ?> 
+2

你可以發表你的JSON? – bksi

+0

對於每個項目,「orderinfo」是否一致,還是有時是數組,有時是JSON字符串? – jterry

+0

json在數組內,但它仍不能解釋爲什麼日期不出現? – Brent

回答

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

看那的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"} 
] 
+0

好吧,這是有道理的,但它應該仍然顯示在它目前只是顯示空白的列表項目中的日期。 – Brent

+0

你試過'$ item ['date']'? – Schleis

+0

是的,只是試圖不能得到它的工作。 – Brent

1

難道只是你的css?具有相同文字顏色的背景顏色?我知道這是愚蠢的,但誰知道...

嘗試print_r($ orderitem);就像你用$ orderdata做的一樣

+0

是試圖去看看,沒有什麼只是一個項目符號列表 – Brent