[英]Create an array with counts of values from another array with the value as a key and the count as the value
I've just surveyed my seven friends about their favourite fruit (not!) and I want to provide the results in an array eg 我刚刚调查了七个朋友关于他们最喜欢的水果的情况(不是!),我想以数组的形式提供结果,例如
Array ( [Apple] => 4 [Orange] => 1 [Strawberry] => 2 [Pear] => 0 ).
I've come up with a solution for this, but it seems in elegant. 我已经为此提出了一个解决方案,但是看起来很优雅。 Is there a way of doing this within the 'foreach', rather than having to use the array combine.
有没有办法在“ foreach”中做到这一点,而不是必须使用数组组合。 Thank you.
谢谢。
// 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);
Just try with array_count_values
只需尝试使用
array_count_values
$fruitcount = array_count_values($favouritefruitlist);
To have also 0
values you, try: 要同时设置
0
值,请尝试:
$initial = array_fill_keys($fruitlist, 0);
$counts = array_count_values($favouritefruitlist);
$fruitcount = array_merge($initial, $counts);
In case you still want to use foreach
instead of array_count_values
, you should loop over $fruitlist
first to build the keys, then over $favouritefruitlist
to populate the array, as such : 如果仍然要使用
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);
Result : 结果:
Array
(
[Apple] => 4
[Orange] => 1
[Strawberry] => 2
[Pear] => 0
)
(BTW, I can't believe none of your friends like pears...) (顺便说一句,我不敢相信您的朋友都不会喜欢梨...)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.