如何最简单地创建一个二维数组?我希望能够做类似于这样的事情:
declare int d[0..m, 0..n]
我喜欢这种方式:
$cars = array
(
array("Volvo",22),
array("BMW",15),
array("Saab",5),
array("Land Rover",17)
);
// You can define your 2D array like this ...
$numbers = [[1, 2], [3, 4]];
// ... or for Questions and Answers like this ...
$QaA = [
['Question_1', 'Answer_1'],
['Question_2', 'Answer_2'] ];
// ... and return some very value like this ...
echo $QaA[1][1]; // "Answer_2"
// And you can browse through all this 2D array:
foreach ( $QaA as $nr1 => $content ) {
echo "\n";
foreach ($content as $nr2 => $answer) {
echo " $nr1, $nr2: $answer"; } }
/* Result:
0, 0: Question_1 0, 1: Answer_1
1, 0: Question_2 1, 1: Answer_2 */
// Thus you can see all the array:
print_r($QaA); /* Result:
Array (
[0] => Array (
[0] => Question_1
[1] => Answer_1 )
[1] => Array (
[0] => Question_2
[1] => Answer_2 ) ) */
$array = Arr::setNestedElement([], '1.2.3', 'value');
这将产生
[
1 => [
2 => [
3 => 'value'
]
]
]
很晚参加派对,但对于现在寻找这方面信息的任何人 - 如果你想要像在C#中声明一个二维数组一样简单地声明它,可以按照以下方式在作用域中声明:
<?php
$My2dArray = array(array());
//This allows you to use it as a bidimensional array. See this loop for example:
for($i = 0; $i < 5; $i++) {
$My2dArray[$i]["whatever-you-want"] = "MyValue";
}
return $My2dArray;
?>