1

我正在尝试获取一个 foreach 循环来显示数组的所有值,但由于某种原因它跳过了值 4。

echo $sku."<br>";
$skuArray = explode(" ", $sku);
$skuCount = array_count_values($skuArray);
print_r($skuArray);
echo "<br><br>";
$i=0;
foreach ($skuCount as $key => $val) {
    echo "[".$i."] => ".$key." ";
    $i++;
}

这就是输出的样子:

1DALI0SPBA775RW 2 $92.99 1GJESSGRIP10000 2 $9.99

Array ( [0] => 1DALI0SPBA775RW 
        [1] => 2 
        [2] => $92.99 
        [3] => 1GJESSGRIP10000 
        [4] => 2 
        [5] => $9.99 )

[0] => 1DALI0SPBA775RW 
[1] => 2 
[2] => $92.99 
[3] => 1GJESSGRIP10000 
[4] => $9.99

如您所见,foreach 循环说 4 等于 $9.99,但在 print_r 数组中它等于 2 - 这是我所期望的。

4

1 回答 1

3

这就是你想要的:

echo $sku."<br>";
$skuArray = explode(" ", $sku);
print_r($skuArray);
echo "<br><br>";
$i=0;
foreach ($skuArray as $key => $val) {
    echo "[".$key."] => ".$val." ";
}

array_count_values($skuArray)实际上创建了一个可以循环的数组,但重复项被省略为单个值。请参阅文档

于 2012-05-15T18:07:13.623 回答