doubi6303 2017-07-20 10:14
浏览 71
已采纳

使用另一个数组中的值计数创建一个数组,其值为键,计数为值

I've just surveyed my seven friends about their favourite fruit (not!) and I want to provide the results in an array e.g.

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. 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);
  • 写回答

2条回答 默认 最新

  • donglu9743 2017-07-20 10:32
    关注

    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 :

    <?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...)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算