![](/img/trans.png)
[英]Iterate through every single key and value in a multi-dimensional associative array 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.