如何初始化PHP二维数组

时间:2010-10-07 14:20:44

标签: php multidimensional-array

假设我想管理像(伪代码)那样的多维数组:

Array $colors
* wine,red
* cheese,yellow
* apple, green
* pear,brown

可以使用什么代码来避免以下表示法来初始化数组(假设有一个硬编码的元素列表=?:

$colors[x][y] = 'something';

4 个答案:

答案 0 :(得分:4)

$array = array(
   array('wine', 'red'),
   array('cheese', 'yellow'),
   array('apple', 'green'),
   array('pear', 'brown')
);

UPD:

foreach ($array as $v) {
   echo $v[0]; // wine, cheese...
   echo $v[1]; // red, yellow...
}

答案 1 :(得分:3)

假设您不想要关联数组,因为您的问题没有提到它。

这是PHP提供的优雅语法:

<?php
$colors = array(array("wine","red"),
                array("cheese","yellow"),
                array("apple", "green"),
                array("pear", "brown"));

print_r($arr); // Prints out an array as shown in output
?>

输出:

    Array
(
    [0] => Array
        (
            [0] => wine
            [1] => red
        )

    [1] => Array
        (
            [0] => cheese
            [1] => yellow
        )

    [2] => Array
        (
            [0] => apple
            [1] => green
        )

    [3] => Array
        (
            [0] => pear
            [1] => brown
        )

)

循环访问所有0:

for($x = 0; $x < count($colors); $x++){
    echo $colors[$x][0];
}

可选地

for($colors as $couple){
   echo $couple[0];
}

编辑:看起来你实际上可能会更好地使用关联..

$colors = array("wine"   => "red",
                "cheese" => "yellow",
                "apple"  => "green",
                "pear"   => "brown");

因为您仍然可以访问密钥,因此:

 for($colors as $key => $value){
       echo $key . " is " . $value;
    }

答案 2 :(得分:1)

答案 3 :(得分:0)

$colors = array(
    array('wine' => 'red',
        'cheese' => 'yellow',
        'apple' => 'green',
        'pear' => 'brown'
    )
);