我是php的新手。
当我print_r($documents)
时,系统将显示:
数组([0] => stdClass对象([id] => 1 [标题] =>“AAA”[摘要] => blablabla [得分] => 100 [主题] =>技术)[1] => stdClass对象([id] => 2 [title] =>“BBB”[summary] => blablabla [得分] => 86 [主题] =>食物)[ 2] => stdClass对象([id] => 3 [title] =>“CCC”[summary] => blablabla [得分] => 45 [主题] =>技术)[3] = > stdClass对象([id] => 4 [title] =>“DDD”[summary] => blablabla [得分] => 67 [主题] =>技术)[4] => stdClass对象([id] => 5 [title] =>“EEE”[summary] => blablabla [得分] => 88 [主题] =>技术))
我想计算'主题'并在该对象上找到最高'得分',所以我有一个结果:
主题“技术”= 4个文件
主题“食物”= 1份文件
文件“AAA”中的最高分= 100
foreach功能怎么办?
foreach($documents as $data)
{
$id = $data->id;
$title = $data->title;
$score = $data->score;
$topic = $data->topic;
}
感谢您的帮助。
答案 0 :(得分:1)
$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);
您可以获取$top
对象的任何属性。您还可以在$group
数组中为每个主题分组。