打印多维数组

时间:2016-02-24 16:44:26

标签: php arrays multidimensional-array

我在PHP中有这个代码:

$rules = array(
    "s0" => array(
        "a" => "s1_s2_s3",
        "b" => "s2_s3"    
    ),
    "s1_s2" => array(
        "a" => "s1_s2",
        "b" => "s2_s3"
    ),
);

想要像这样打印:

s0 -- a --- s1_s2_s3
s0 -- b --- s2_s3
s1_s2 -- a --- s1_s2
s1_s2 -- b --- s2_s3

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您就是这样做的:

$rules = array(
    "s0"  => array(
        "a" => "s1_s2_s3",
        "b" => "s2_s3"
    ),
    "s1_s2" => array(
        "a" => "s1_s2",
        "b" => "s2_s3"
    ),
);


foreach ($rules as $key => $args) {
    foreach ($args as $key2 => $vals) {
        print $key . ' -- ' . $key2 . ' --- ' . $vals . '<br>';
    }
}


编辑阵列

您可以使用array_push[]

array_push($rules, ['another' => ['c' => 'value']]);
$rules['another'] = ['c' => 'value']];

在索引处添加或更新数组:

$rules['another']['c'] = 'change c value';

答案 1 :(得分:0)

要实现这一点,您必须遍历数组。要做到这一点,你需要一个循环,在PHP中,有一个函数foreach。这是一个例子 -

给定数组:

$rules = array("s0" => array("a" => "s1_s2_s3",
                              "b" => "s2_s3"    
                              ),
               "s1_s2" => array("a" => "s1_s2",
                                "b" => "s2_s3"
                               )
                );

foreach ($rules as $key => $value) {
    foreach ($value as $sub_key => $sub_val) {
        echo "<p>".$key." -- ".$sub_key." --- ".$sub_val."</p>";
    }
}

foreach构造提供了一种迭代数组的简单方法。

<强>输出:

s0 -- a --- s1_s2_s3
s0 -- b --- s2_s3
s1_s2 -- a --- s1_s2
s1_s2 -- b --- s2_s3