【问题标题】:How to iterate only the first 3 elements of an array and access the keys/values?如何仅迭代数组的前 3 个元素并访问键/值?
【发布时间】:2019-02-04 08:58:09
【问题描述】:

我试图根据每个卖家销售的产品数量为他们分配每月积分。然而,这些数字只是一个例子。 到目前为止,这是我的代码:

$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>

【问题讨论】:

  • $sellers 数组在哪里?
  • 你的问题是?
  • 回显不显示总分。
  • 您无法访问那些带有数字的关联键 ($a)。您只想显示前三个元素/卖家吗?
  • 我不明白 while 循环的概念。卖家名称是数组键,数组字段值就是你要找的。​​span>

标签: php arrays loops slice


【解决方案1】:

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

代码:(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;
}

【讨论】:

  • 但是如果最后一条记录的销售额最高呢?如果我没记错的话,前 3 个总是正确的?
  • 样本输入显然已经排序。如果你问我是否知道如何对一维数组 DESC 进行排序,答案是“是”。 php.net/manual/en/function.arsort.php
【解决方案2】:

为什么在 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++;
}

【讨论】:

  • 我的反馈: 1. 打电话给array_flip() 没有意义 2. 继续迭代并且不执行任何操作是不好的做法。 3. 考虑到值是关联键,$index 不是逻辑变量名。 ($name$key 会更好)
猜你喜欢
  • 1970-01-01
  • 2013-11-23
  • 1970-01-01
  • 2021-01-30
  • 2020-07-26
  • 2016-01-09
  • 2013-01-05
  • 2018-08-16
  • 2022-07-12
相关资源
最近更新 更多