[[+content_image]]
D
D
Dmitry Morozov2018-12-27 10:45:42
PHP
Dmitry Morozov, 2018-12-27 10:45:42

PHP Associative array, how to filter by largest values?

Good day, there is an associative array:

$arr = [['name' => 'ford', 'count' => 2], ['name' => 'ford', 'count' => 8], ['name' => 'lada', 'count' => 9], ['name' => 'lada', 'count' => 2]]

How to get the largest value of brand names from this array?
Expected output - ford - 8, lada - 9

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
R
Roman, 2018-12-27
@index1

As an option

$arr = [['name' => 'ford', 'count' => 2],
    ['name' => 'ford', 'count' => 8],
    ['name' => 'lada', 'count' => 9],
    ['name' => 'lada', 'count' => 2]];

$result = [];
foreach($arr as $car) {
    if (!isset($result[$car['name']]) || $result[$car['name']] < $car['count']) {
        $result[$car['name']] = $car['count'];
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question