如何通过使用PHP中的foreach循环仅获取数组的前两个元素?

时间:2019-02-15 12:31:09

标签: php arrays loops foreach element

我有一个像这样的数组:

$aMyArray = array(
            "bmw"=>"user1",
            "audi"=>"user2",
            "mercedes"=>"user3"
);

我只想显示前两个元素bmw=>user1audi=>user2。 但是我想通过使用foreach循环来实现。

6 个答案:

答案 0 :(得分:3)

如果要按名称输入前两个:

您要使用in_arraydocumentation

$aMyArray = array("bmw"=>"user1", "audi"=>"user2", "mercedes"=>"user3");
$valuesToPrint = array("bmw", "audi");
foreach($aMyArray as $key => $val) {
    if (in_array($key, $valuesToPrint))
        echo "Found: $key => $val" . PHP_EOL;
}

如果要按索引使用前2个:

初始索引为0,并在每次迭代中递增为:

$aMyArray = array("bmw"=>"user1", "audi"=>"user2", "mercedes"=>"user3");
$i = 0;
foreach($aMyArray as $key => $val) {
    echo "Found: $key => $val" . PHP_EOL;
    if (++$i > 1)
        break;
}

答案 1 :(得分:0)

最简单的方法:

$aMyArray=array("bmw"=>"user1","audi"=>"user2","mercedes"=>"user3");
$i=0;
foreach ($aMyArray as $key => $value) {
 if($i<2)
 {
    echo $key . 'and' . $value;
 }
 $i++;
}

答案 2 :(得分:0)

<?php
$aMyArray = array(
            "bmw"=>"user1",
            "audi"=>"user2",
            "mercedes"=>"user3"
);

reset($aMyArray);
echo key($aMyArray).' = '.current($aMyArray)."\n";
next($aMyArray);
echo key($aMyArray).' = '.current($aMyArray)."\n";

答案 3 :(得分:0)

$counter = 1;
$max = 2;
foreach ($aMyArray as $key => $value) {
    echo $key, "=>", $value;
    $counter++;
    if ($counter === $max) {
        break;
    }
}

重要的是中断执行以避免任何大小的数组无休止地循环到结尾。

答案 4 :(得分:0)

我知道您在问如何在foreach中进行操作,但是另一个选择是使用数组移动函数currentnext

$aMyArray = array(
            "bmw"=>"user1",
            "audi"=>"user2",
            "mercedes"=>"user3"
);
$keys = array_keys($aMyArray);
//current($array) will return the value of the current record in the array. At this point that will be the first record
$first = sprintf('%s - %s', current($keys), current($aMyArray)); //bmw - user1
//move the pointer to the next record in both $keys and $aMyArray
next($aMyArray);
next($keys);
//current($array) will now return the contents of the second element.
$second = sprintf('%s - %s', current($keys), current($aMyArray)); //audi - user2

答案 5 :(得分:-1)

您正在寻找类似的东西

$aMyArray = array(
            "bmw"=>"user1",
            "audi"=>"user2",
            "mercedes"=>"user3"
);
foreach($aMyArray as $k=>$v){
    echo $v;
    if($k=='audi'){
        break;
    }
}