2017-07-20 16 views
1

私は自分の7人の友人に自分の好きなフルーツについて質問しましたが、私はその結果をアレイ値をキーに、カウントを値として別の配列の値の数を持つ配列を作成する

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

'array_count_values'方法は、この場合に役立つはず。 –

+0

それは 1を働くので、私は実際に上記の編集をする簡単な方法を見つけた)array_combineビットを削除する「$のfruitcount [$ favouritefruit] =カウント数」 2)に「$のfruitcount [] =カウント数」からそれを変更します –

答えて

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 
) 

(ところで、私は梨のようなあなたの友人のどれを信じることはできません...)

4

だけでも、あなたは、してみてください0値持つためにarray_count_values

$fruitcount = array_count_values($favouritefruitlist); 

で試してみてください。

$initial = array_fill_keys($fruitlist, 0); 
$counts = array_count_values($favouritefruitlist); 
$fruitcount = array_merge($initial, $counts); 
+0

ありがとうございます。この問題は、フルーツの数が0である場合(例えば、梨)、それが$ fruitcount配列にないことです。0 –

+0

@LinzDarlington Okと、私の編集を確認してください。 – hsz

関連する問題