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 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测