doudi1978 2014-11-13 07:27
浏览 37
已采纳

为php中的热门书籍排序数组

Here's an problem where i have to find the top book and the number of readers for each book in php . The array is something as below

$input=array();
$input[]=array("Harrypotter","John");
$input[]=array("Twilight","Jack");
$input[]=array("Twilight","John");
$input[]=array("Harrypotter","Jack");
$input[]=array("Gonegirl","marion");
$input[]=array("Gonegirl","marion");
$input[]=array("Gonegirl","John");
$input[]=array("Gonegirl","eliza");

i can find the top book by copying the book names onto a separate array say temparray and use the following functions

$temparray = array_count_values($temparray);
arsort($temparray);

but i'm not able to figure out on the logic how to get the number of readers for each book,the reader names may repeat so we have to eliminate the repeated ones .Any quick way to sort the thing would be helpful.

  • 写回答

2条回答 默认 最新

  • dqdmvg7332 2014-11-13 07:31
    关注

    You could get each book name first to create a flat array, then apply the count. Example:

    $input=array();
    $input[]=array("Harrypotter","John");
    $input[]=array("Twilight","Jack");
    $input[]=array("Twilight","John");
    $input[]=array("Harrypotter","Jack");
    $input[]=array("Gonegirl","marion");
    $input[]=array("Gonegirl","test");
    $input[]=array("Gonegirl","John");
    $input[]=array("Gonegirl","eliza");
    
    $input = array_map('unserialize', array_unique(array_map('serialize', $input)));
    // remove dups
    $temparray = array_map(function($book_name){
        return $book_name[0]; // get book names
    }, $input);
    $temparray = array_count_values($temparray); // then apply the counting
    arsort($temparray);
    
    print_r($temparray); // Array ( [Gonegirl] => 3 [Twilight] => 2 [Harrypotter] => 2 )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计