如何仅迭代数组的前三个元素并访问键/值?

时间:2018-08-29 14:16:49

标签: php arrays loops slice

我试图根据他们销售的产品数量为每个卖方分配每月积分。但是,数字仅是示例。 到目前为止,这是我的代码:

$sellers = array(
    'Edvin'   => 10, 
    'Julio'   =>  9, 
    'Rene'    =>  8, 
    'Jorge'   =>  7, 
    'Marvin'  =>  6,
    'Brayan'  =>  5, 
    'Sergio'  =>  4,   
    'Delfido' =>  3, 
    'Jhon'    =>  2
);

$a = 1;
foreach ($sellers as $seller => $points) {
    while ($a < 4) {
        echo "The seller top " . $a . " is " . $sellers[$a - 1] . ' with ' . $points[$a] . '<br>';
        $a++;
    }
}

我正在尝试输出:

The seller top 1 is Edvin with 10<br>
The seller top 2 is Julio with 9<br>
The seller top 3 is Rene with 8<br>

2 个答案:

答案 0 :(得分:0)

您只想访问前三个元素,因此在循环之前对数组进行切片,可以在迭代时递增计数器。

代码:(Demo

$sellers = array('Edvin' => 10, 'Julio' => 9, 'Rene' => 8, 'Jorge' =>7, 'Marvin' => 6,
                    'Brayan' => 5, 'Sergio' => 4, 'Delfido' => 3, 'Jhon' => 2);

$i = 0;
foreach (array_slice($sellers, 0, 3) as $seller => $points) {
    echo "The seller top " . ++$i . " is $seller with $points<br>";
}

输出:

The seller top 1 is Edvin with 10<br>
The seller top 2 is Julio with 9<br>
The seller top 3 is Rene with 8<br>

如果要使用计数器控制循环并忽略array_slice()调用,则需要编写循环中断。

$i = 0;
foreach ($sellers as $seller => $points) {
    echo "The seller top " . ++$i . " is $seller with $points<br>";
    if ($i == 3) break;
}

答案 1 :(得分:0)

为什么在foreach循环中使用While循环?

您可以这样做:

$sellers = array(
  'Edvin'   => 10,
  'Julio'   =>  9,
  'Rene'    =>  8,
  'Jorge'   =>  7,
  'Marvin'  =>  6,
  'Brayan'  =>  5,
  'Sergio'  =>  4,
  'Delfido' =>  3,
  'Jhon'    =>  2
);

$a = 1;
foreach (array_flip($sellers) as $points => $seller) {
  if ($a < 4) {
    echo "The seller top " . $a . " is " . $seller . ' with ' . $points . '<br>';
    $a++;
   }
 }

如果要使用while循环,可以执行以下操作:

$sellers = array(
  'Edvin'   => 10,
  'Julio'   =>  9,
  'Rene'    =>  8,
  'Jorge'   =>  7,
  'Marvin'  =>  6,
  'Brayan'  =>  5,
  'Sergio'  =>  4,
  'Delfido' =>  3,
  'Jhon'    =>  2
);

$a = 0;
// Get Associative Keys
$keys = array_keys($sellers);
while($a < 3){
    // Get Assoc INDEX at position
    $index = $keys[$a];

    echo "The seller top " . ($a+1) . " is " . $index . ' with ' . $sellers[$index] . '<br>';
    $a++;
}