簡體   English   中英

在php中創建,訪問和理解多維數組

[英]Creating, Accessing and understanding multidimensional arrays in php

我實現了以下小示例:

$nodeList;  
for($i = 0; $i < 10;$i++) {
    $nodeList[$i] = $i;
    for($j = 0; $j < 3;$j++) {
        $nodeList[$i][$j] = $j;
    }
}

foreach($nodeList[0] as $nodeEl) {
    print "NodeEl: ".$nodeEl." | ";
}

print nl2br("\n\r");

$testList = array
  (
  array(1,2,3),
  array(4,5,6),
  array(7,8,9),
  array(10,11,12),
  );
foreach($testList[0] as $testEl) {
    print "TestEl: ".$testEl." | ";
}

其中$nodeList的輸出為null (也是var_dump / print_r), $testList的輸出為TestEl: 1 | TestEl: 2 | TestEl: 3 TestEl: 1 | TestEl: 2 | TestEl: 3 TestEl: 1 | TestEl: 2 | TestEl: 3 ,符合預期。

以我的理解,這兩個解決方案應該創建大致相同的輸出-但是,第一個解決方案根本沒有輸出。 因為甚至沒有創建數組的第二維。

http://php.net/manual/de/language.types.array.php上閱讀后,會產生強烈的感覺,即[]運算符僅用於解引用/訪問數組,但是文檔再次提供了示例,其中他們以與我執行$arr["x"] = 42相同的方式為某個鍵分配值。

這兩種數組訪問方式有什么區別?

如何以類似於嘗試填充$nodeList的方式實現填充n維數組?

您應該確保已打開錯誤報告,因為會為您的代碼生成警告:

E_WARNING :  type 2 -- Cannot use a scalar value as an array -- at line 7

這涉及以下語句:

$nodeList[$i] = $i;

如果要創建2D數組,則在第一級分配數字沒有任何意義。 相反,您希望$nodeList[$i]是一個數組。 當您使用方括號[...]訪問PHP時,PHP會隱式地執行此操作(創建數組),因此您可以省去有問題的語句,然后執行以下操作:

for($i = 0; $i < 10;$i++) {
    for($j = 0; $j < 3;$j++) {
        $nodeList[$i][$j] = $j;
    }
}

您甚至可以在最后一個括號對中省略$j ,這意味着PHP將使用下一個可用的數字索引將其添加到數組中:

for($i = 0; $i < 10;$i++) {
    for($j = 0; $j < 3;$j++) {
        $nodeList[$i][] = $j;
    }
}

在每個級別增加價值

如果確實需要將$i存儲在2D數組的第一級,則考慮使用更復雜的結構,其中每個元素是具有兩個鍵的關聯數組:一個用於值,另一個用於嵌套數組:

for($i = 0; $i < 10; $i++) {
    $nodeList[$i] = array(
        "value" => $i,
        "children" => array()
    );
    for($j = 0; $j < 3;$j++) {
        $nodeList[$i]["children"][] = array(
            "value" => "$i.$j" // just example of value, could be just $j
        );
    }
}

$nodeList將會像這樣:

array (
  array (
    'value' => 0,
    'children' => array (
      array ('value' => '0.0'),
      array ('value' => '0.1'),
      array ('value' => '0.2'),
    ),
  ),
  array (
    'value' => 1,
    'children' => array (
      array ('value' => '1.0'),
      array ('value' => '1.1'),
      array ('value' => '1.2'),
    ),
  ),
  //...etc
);

你應該寫

<?php

$nodeList;  
for($i = 0; $i < 10;$i++) {
    for($j = 0; $j < 3;$j++) {
        $nodeList[$i][$j] = $j;
    }
}

foreach($nodeList[0] as $nodeEl) {
    print "NodeEl: ".$nodeEl." | ";
}

您需要將$nodeList聲明為數組,例如

$nodeList=array();

對於二維數組

$nodeList= array(array());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM