phparraysmultidimensional-arrayfiltermin

Find id column value of row containing the lowest value in a specified column of a 2d array


I have read several similar questions on here, such as this, Finding the minimum value's key in an associative array but I think my problem may be unique in that my source array is not strings as keys.

My source array looks like this,

$dealers = [
    ['id' => 1526, 'count' => 2],
    ['id' => 1518, 'count' => 5],
    ['id' => 1511, 'count' => 9],
    ['id' => 1410, 'count' => 3],
];

I need to get the id of the smallest count value.

I have tried the following,

$low_dealer = array_keys($dealers, min($dealers));

But it appears to be returning the index of the lowest id and not count.

My next attempt was combining another function I found to find the min of the specific column,

$low_dealer = array_keys($dealers, min( array_column( $dealers, 'count' ) ));

But that returned nothing.

EDIT: Also must be able to handle multiple mins, if two or more rows have the same count number, need to get an array of them back so I can rand() it.


Solution

  • $dealersMin = min(array_column($dealers, 'count'));
    
    $dealersWithMinCount = array_filter($dealers, function ($dealer) {
        global $dealersMin;
        return ($dealer['count'] == $dealersMin);
    });
    
    var_dump($dealersWithMinCount[array_rand($dealersWithMinCount)]['id']);
    

    Explanation

    1. First we find the lowest value of 'count' in the array and save that to $dealersMin.
    2. Then we need to get all rows in the $dealers array that have a count of $dealersMin and save that in $dealersWithMinCount.
    3. Then just pick a random element of $dealersWithMinCount with array_rand()