Home >Backend Development >PHP Tutorial >How to Find the Element with the Highest 'Total' Value in a Multidimensional Array?

How to Find the Element with the Highest 'Total' Value in a Multidimensional Array?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-10 01:30:02357browse

How to Find the Element with the Highest

Identifying the Maximal Element in a Multidimensional Array

You have a multidimensional array where each element contains various key-value pairs, including a "Total" key. Your goal is to determine the element with the highest "Total" value.

Using the array_column() Function

To extract an array containing only the "Total" values, you can utilize the array_column() function. It takes an array and a key as arguments, returning an array containing the values associated with the specified key.

$totals = array_column($array, 'Total');

Finding the Maximum

Once you have the "Total" values in a separate array, you can use the max() function to determine the highest value.

$maxTotal = max($totals);

Retrieving the Associated Data

To retrieve the remaining data associated with the element with the maximum "Total" value, loop through the original array and compare each element's "Total" value to the $maxTotal variable.

foreach ($array as $element) {
    if ($element['Total'] == $maxTotal) {
        // Retrieve and display the associated data
        echo "Highest Total:", $element['Total'];
        echo "Other data:", $element['Key1'], $element['Key2'], $element['Key3'];
        break;
    }
}

The above is the detailed content of How to Find the Element with the Highest 'Total' Value in a Multidimensional Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn