我有一个数组,比如:
$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'];
当然我不能那样做,因为每个键都是一个字符串。有没有一个简单的解决方案,或者我只是愚蠢地编写了这个代码?
编辑:我延长了数组的长度,以充分展示我要做的事情。
array_slice
(docs)就是为此而制作的。
对于前两组水果:
foreach(array_slice($fruits,0,2) as $fruitGroup) echo $fruitGroup['fruit one'];
对于接下来的2个水果组:
foreach(array_slice($fruits,2,2) as $fruitGroup) echo $fruitGroup['fruit one'];
实时演示
这样做的好处是简单(相对于Chrys的解决方案),而且不会破坏数组中的原始密钥。
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