返回for循环中最常出现的值/行

I have a for loop that returns ID's of a list of products contained in a customer's order. Each product ID is associated with a category via a function I cannot modify, and I wanted to get a single category that occurs the most in the returned results.

For example the for loop result returns product IDs: 1 2 3 4

And subsequently those product IDs would be associated with categories: A B B C

How would I return 'B' only, being that it is the most frequently occurring category?

for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) {
    $products = $order->products[$i]['id'];
    echo $products; //return all products
    echo category_name($products); //this function returns all the category names of each ID, but I only want to return the most frequently occurring one without modifying this function
}

One way is to assign them to an array and then array_count_values:

for ($i = 0, $n = sizeof($order->products); $i < $n; $i++) {
    $products = $order->products[$i]['id'];
    echo $products;
    echo $categories[] = category_name($products); //assign to array
}

$result = array_count_values($categories);
arsort($result);
echo $result[0];

If you have more than one category that appears the same number of maximum times then the one appearing last in the array will be returned.

I would use a foreach:

foreach($order->products as $product) {
    echo $product['id'];
    echo $categories[] = category_name($product['id']); //assign to array
}