如何使用PHP打印多维数组?

时间:2014-09-14 15:21:52

标签: php arrays multidimensional-array

我在PHP中有数组被保存到$_SESSION。我想以适当的可读格式和表格形式输出数组。

我尝试将数组内容检查为print_r($_SESSION['post-data']),输出为

Array ( [jcart_item_name] => Array ( [0] => Choley Bhature [1] => Onion Kulcha with 
Chana and Raita [2] => Dal Makhani ) [jcart_item_id] => Array ( [0] => 1 [1] => 
5 [2] => 6 ) [jcart_item_price] =>Array ( [0] => 85 [1] => 90 [2] => 105 ) 
[jcart_item_qty] => Array ( [0] => 3 [1] => 1 [2] => 1[jcart_checkout] => PlaceOrder) 

我想以下列格式输出jcart_item_namejcart_item_qtyjcart_item_price

Item Name       Item Qty    Item Price
--------------------------------------
Choley Bhature     3          50

3 个答案:

答案 0 :(得分:0)

尝试将此数组划分为多个数组,例如:jcart_item_name,jcart_item_qty和jcart_item_price是三个数组。然后,当您的数组具有相同的大小时,您可以使用函数count()sizeof()来获取大小。然后你会得到:     //现在我们有了这三个数组     $ ARR1; // jcart_item_name数组     $ ARR2; // jcart_item_qty数组     $ ARR3; // jcart_item_price数组

$size = sizeof($arr1); //all arrays size is the same


for ($i=0; $i < $size; $i++) {
    //DO WHAT YOU WANT
    echo $arr1[$i]."<br>";
    echo $arr2[$i]."<br>";
    echo $arr3[$i]."<br>";
}

答案 1 :(得分:0)

听起来很好吃...... 你的数组是否需要关联?

<?php
$myArray = Array (
Array ( 1, 5, 6),
Array ('Choley Bhature', 'Onion Kulcha with Chana and Raita', 'Dal Makhani'),
Array (3, 1, 1),
Array (85, 90, 105));

echo "<table><tr><td>Id</td><td>Item Name</td><td>Qty.</td><td>Price</td></tr><br/>";
    for ($j=0; $j<count($myArray[0]); $j++){
        echo "<tr><td>".$myArray[0][$j]."</td><td>".$myArray[1][$j]."</td><td>".$myArray[2][$j]."</td><td>".$myArray[3][$j]."</td>";
    }
echo "</table>";
?>

答案 2 :(得分:0)

我确定你可以自己做格式化,但这就是你得到你想要的价值的方式......

foreach($_SESSION['jcart_item_name'] as $key => $item) {

    echo $item . ' - ' . $_SESSION['jcart_item_qty'][$key] . ' - ' . $_SESSION['jcart_item_price'][$key] . '<br>';

}

我建议以不同的方式构建你的数组......就像这样

$_SESSION['jcart_items'] = array(
     array('name' => 'Choley Bhature', 'price' => 85, 'qty' => 3),
     array('name' => 'Onion Kulcha with Chana and Raita', 'price' => 90, 'qty' => 1)
     ...etc
);

这种方式可以在$ _SESSION [&#39; jcart_items&#39;]上进行简单的foreach循环,并且它更具可读性

foreach($_SESSION['jcart_items'] as $k => $item) {
    echo $item['name'] . ' - ' . $item ['qty'] . ' - ' . $item['price'] . '<br>';
}