我刚刚调查了我的七个朋友关于他们最喜欢的水果(不是!),我想以数组形式提供结果。
Array ( [Apple] => 4 [Orange] => 1 [Strawberry] => 2 [Pear] => 0 ).
我想出了一个解决方案,但看起来很优雅。有没有办法在'foreach'中执行此操作,而不必使用数组合并。谢谢。
// Set the array of favourite fruit options.
$fruitlist = array('Apple', 'Orange', 'Strawberry', 'Pear');
// Survey results from seven people
$favouritefruitlist = array('Apple', 'Apple', 'Orange', 'Apple','Strawberry', 'Apple', 'Strawberry');
// Create an array to count the number of favourites for each option
$fruitcount = [];
foreach ($fruitlist as $favouritefruit) {
$fruitcount[] = count(array_keys($favouritefruitlist, $favouritefruit));
}
// Combine the keys and the values
$fruitcount = array_combine ($fruitlist, $fruitcount);
print_r($fruitcount);
答案 0 :(得分:4)
$fruitcount = array_count_values($favouritefruitlist);
要同时为0
值,请尝试:
$initial = array_fill_keys($fruitlist, 0);
$counts = array_count_values($favouritefruitlist);
$fruitcount = array_merge($initial, $counts);
答案 1 :(得分:1)
如果您仍想使用foreach
而非array_count_values
,则应首先循环$fruitlist
以构建密钥,然后通过$favouritefruitlist
填充数组,就这样:
<?php
// Set the array of favourite fruit options.
$fruitlist = array('Apple', 'Orange', 'Strawberry', 'Pear');
// Survey results from seven people
$favouritefruitlist = array('Apple', 'Apple', 'Orange', 'Apple', 'Strawberry', 'Apple', 'Strawberry');
// Create an array to count the number of favourites for each option
$fruitcount = [];
foreach ($fruitlist as $fruit) {
$fruitcount[$fruit] = 0;
}
foreach ($favouritefruitlist as $favouritefruit) {
$fruitcount[$favouritefruit]++;
}
print_r($fruitcount);
结果:
Array
(
[Apple] => 4
[Orange] => 1
[Strawberry] => 2
[Pear] => 0
)
(顺便说一句,我不能相信你的朋友都不喜欢梨......)