Raider
Raider

Reputation: 53

Find row in 2d array with specific value in a column and smallest value in another column

I have the following 2D array and I would like to get the key of the smallest value in the [0] column if done is equal to no.

$graph= array(
"CityA" => array(
    "0" => "1",
    "1" => "CityC",
    "done" => "no",
    ),
"CityB" => array(
    "0" => "4",
    "1" => "CityA",
    "done" => "no",
    ),
"CityC" => array(
    "0" => "5",
    "1" => "CityA",
    "done" => "no",
    ),
);

Upvotes: 1

Views: 753

Answers (3)

mickmackusa
mickmackusa

Reputation: 47874

You should perform all of your checks in a single pass through your array.

My snippet will provide the first qualifying (contains the lowest [0] value AND has a done value of no) row's key.

Code: (Demo)

$graph = [
    "CityB" => ["0" => "1", "1" => "CityA", "done" => "no"],
    "CityA" => ["0" => "1", "1" => "CityC", "done" => "no"],
    "CityD" => ["0" => "1", "1" => "CityD", "done" => "yes"],
    "CityC" => ["0" => "5", "1" => "CityA", "done" => "no"]
];

$result = [];
foreach ($graph as $key => $row) {
    if ($row['done'] === 'no' && (!isset($result[$key]) || $row[0] < $result[$key])) {
        $result[$key] = $row[0];
    }
}

echo key($result) ?? 'No "done => no" rows';

Output:

CityB

Upvotes: 0

Ukasha
Ukasha

Reputation: 2334

Here you go.

$tes = min( array_column( $graph, 0 ) );
$key = array_search( $tes, array_column( $graph, 0 ) );
$array_keys = array_keys($graph);

echo $array_keys[$key];

Upvotes: 0

LF-DevJourney
LF-DevJourney

Reputation: 28529

Try this,

$arr = array_map(function($v){return $v[0];}, $graph);
$key = array_keys($arr, min($arr));

Upvotes: 4

Related Questions