按行输出数组

时间:2013-01-10 16:52:07

标签: php arrays

有一个数组:

Array
(
    [33] => Array
        (
            [0] => 1
            [1] => 1
            [2] => 5
            [3] => 2
            [4] => 1
            [5] => 1
            [6] => 2
        )

    [22] => Array
        (
            [0] => 1
            [1] => 5
            [2] => 5
        )

    [11] => Array
        (
            [0] => 1
        )

)

在php中打印输出此数组的更好方法是什么?:

raw1:33(1);22(1);11(1);
raw2:33(1);22(5);11();
raw3:33(5);22(5);11();
raw4:33(2);22();11();
raw5:33(1);22();11();
raw6:33(1);22();11();
raw7:33(2);22();11();

2 个答案:

答案 0 :(得分:1)

你需要的只是

$data = array(
  33 => array(
    0 => 1,
    1 => 1,
    2 => 5,
    3 => 2,
    4 => 1,
    5 => 1,
    6 => 2,
  ),
  22 => array(
    0 => 1,
    1 => 5,
    2 => 5,
  ),
  11 => array(
    0 => 1,
  ),
);

$x = 1;
foreach ( new ColumnIterator($data) as $set ) {
    echo "raw$x:";
    foreach ( $set as $k => $v )
        echo $k . "($v);";
    echo "\n";
    $x ++;
}

输出

raw1:33(1);22(1);11(1);
raw2:33(1);22(5);11();
raw3:33(5);22(5);11();
raw4:33(2);22();11();
raw5:33(1);22();11();
raw6:33(1);22();11();
raw7:33(2);22();11();

Online Demo

使用的课程

class ColumnIterator extends MultipleIterator {
    function __construct(array $multi) {
        parent::__construct(self::MIT_NEED_ANY | self::MIT_KEYS_ASSOC);
        foreach ( $multi as $k => $v ) {
            $this->attachIterator(new ArrayIterator($v), $k);
        }
    }
}

答案 1 :(得分:0)

你可以试试这个 -

for($loop=0;$loop<count($array[33]);$loop++) {
    $arr1 = ($arr[33][$loop]) ? $arr[33][$loop] : "";
    $arr2 = ($arr[22][$loop]) ? $arr[22][$loop] : "";
    $arr3 = ($arr[11][$loop]) ? $arr[11][$loop] : "";
    echo "row".$loop+1.":33(".$arr1.");22(".$arr2.");11(".$arr3.")";
}