簡體   English   中英

當每個鍵都是一個字符串時,迭代PHP中的多維關聯數組

[英]Iterate through multidimensional associative array in PHP when every key is a string

我有一個像這樣的數組:

$fruits = array(
  'citrus' => array(
    'fruit one' => 'orange',
    'fruit two' => 'lime',
  ),
  'melon' => array(
    'fruit one' => 'honeydew',
    'fruit two' => 'cantalope',
  ),
  'berry' => array(
    'fruit one' => 'raspberry',
    'fruit two' => 'strawberry',
  ),
  'apple' => array(
    'fruit one' => 'granny smith',
    'fruit two' => 'fuji',
  )

);

我希望能夠訪問它的切片,比如echo $fruits[0]['fruit one']; 這樣我就可以創建一個for循環來獲取數組的特定組。 我的意思是,我理想情況下可以這樣做:

for($i = 0; $i <= 1; $i++)
  echo $fruit[$i]['fruit one'];

// Then some other code

for($i = 2; $i <= 3; $i++)
  echo $fruit[$i]['fruit one'];

當然我不能這樣做,因為每個鍵都是一個字符串。 是否有一個簡單的解決方案,或者我只是愚蠢地編碼?

編輯 :我讓數組更長,以充分展示我正在嘗試做的事情。

foreach ( $fruits AS $fruit ) {
  foreach ( $fruit AS $subFruit ) {
    // insert code here
  }
}
function replaceKeys(&$array)
{
    $ptr = null;
    foreach ($array as $values) {
        $ptr[] = $values;
    }
    $array = $ptr;
}

$fruits = array(
  'citrus' => array(
    'fruit one' => 'orange',
    'fruit two' => 'lime',
  ),
  'melon' => array(
    'fruit one' => 'honeydew',
    'fruit two' => 'cantalope',
  )
);


replaceKeys($fruits);

var_dump($fruits[0]['fruit one']);

//Output: orange

array_slicedocs )就是為此而制作的。

對於前2個水果組:

foreach(array_slice($fruits,0,2) as $fruitGroup) echo $fruitGroup['fruit one'];

對於接下來的兩個水果組:

foreach(array_slice($fruits,2,2) as $fruitGroup) echo $fruitGroup['fruit one'];

現場演示

這具有簡單的優點(超過Chrys的解決方案),並且不會破壞陣列中的原始密鑰。

暫無
暫無

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

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