duancai7568 2013-05-14 03:09
浏览 30
已采纳

从对象php中的数组计数数据

I'm new in php.

When i print_r($documents), the system will display:

Array ( [0] => stdClass Object ( [id] => 1 [title] => "AAA" [summary] => blablabla [score] => 100 [topic] => Technology ) [1] => stdClass Object ( [id] => 2 [title] => "BBB" [summary] => blablabla [score] => 86 [topic] => Food ) [2] => stdClass Object ( [id] => 3 [title] => "CCC" [summary] => blablabla [score] => 45 [topic] => Technology ) [3] => stdClass Object ( [id] => 4 [title] => "DDD" [summary] => blablabla [score] => 67 [topic] => Technology ) [4] => stdClass Object ( [id] => 5 [title] => "EEE" [summary] => blablabla [score] => 88 [topic] => Technology ))

I want to count 'topic' and find a highest 'score' on that object, so i have a result:

Topic "Technology" = 4 documents

Topic "Food" = 1 document

Highest score = 100 in document "AAA"

What can i do with foreach function?

foreach($documents as $data)
{
    $id = $data->id;
    $title = $data->title;
    $score = $data->score;
    $topic = $data->topic;
}

Thanks for your help.

  • 写回答

1条回答 默认 最新

  • dongzhuang6417 2013-05-14 03:20
    关注
    $top   = $documents[0]; // top element (with max score, assume first one as default)
    $group = array();       // group buffer to store document count
    
    foreach($documents as $data){
       $topic = $data->topic;
    
       // if topic in group
       if(isset($group[$topic])){
           $group[$topic]++;   // add one document
       } else { // otherwise
           $group[$topic] = 1; // set one document
       }
    
       // if $tops's score value is lesser than current $data's value
       if($top->score < $data->score){
           $top = $data; // there is a new top.
       }
    }
    
    var_dump($group, $top);
    

    You may aquire any property of $top object. Also you have group count for each topic in $group array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度