0

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 Answer 1

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);

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.