假设我有一个看起来像这样的数组
array ([apple] => 1, [dog]=>2, [cat]=>5, [bread]=>9, [shoes]=> 4)
我能否打印出数组的前三个值?如果可以,怎么做?有什么想法吗?
$firstThreeElements = array_slice($array, 0, 3);
0是你的偏移量,3是你想要的元素数量。
有很多方法。
list( $first, $second, $third) = $array;
echo $first . ' ' . $second . ' ' . $third;
或者:echo array_shift( $array);
echo array_shift( $array);
echo array_shift( $array);
或者:
$i = 0;
foreach( $array as $el) {
if( $i >= 3) break;
echo $el;
$i++;
}
或者:
foreach( array_slice( $array, 0, 3) as $el) {
echo $el;
}
或者:
echo implode( ' ', array_slice( $array, 0, 3));
foreach( $array as $i=>$el)
可以翻译为:foreach($array as $i=>$el)
。 - Ben$i
将包含键,这是一个关联数组。 - nickbarray_slice
的解决方案可能是最紧凑和未来证明的。当需求改变时,list
和 array_shift
会变得越来越冗长,而在涉及计数器时,foreach
总是很丑陋的。 - Matthew使用迭代器:
$array = ['apple' => 1, 'dog' => 2, 'cat' => 5, 'bread' => 9, 'shoes' => 4];
foreach (new LimitIterator(new ArrayIterator($array), 0, 3) as $key => $val)
{
echo "$key => $val\n";
}