Counting data from array in object php -
i'm new in php.
when print_r($documents)
, system 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 count 'topic' , find highest 'score' on object, have result:
topic "technology" = 4 documents
topic "food" = 1 document
highest score = 100 in document "aaa"
what can foreach function?
foreach($documents $data) { $id = $data->id; $title = $data->title; $score = $data->score; $topic = $data->topic; }
thanks help.
$top = $documents[0]; // top element (with max score, assume first 1 default) $group = array(); // group buffer store document count foreach($documents $data){ $topic = $data->topic; // if topic in group if(isset($group[$topic])){ $group[$topic]++; // add 1 document } else { // otherwise $group[$topic] = 1; // set 1 document } // if $tops's score value lesser current $data's value if($top->score < $data->score){ $top = $data; // there new top. } } var_dump($group, $top);
you may aquire property of $top
object. have group count each topic in $group
array.
Comments
Post a Comment