1

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",
    ),
);
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Raider
  • 53
  • 8
  • Possible duplicate of [Find min/max in a two dimensional array](http://stackoverflow.com/questions/28372241/find-min-max-in-a-two-dimensional-array) – Sean May 21 '17 at 14:42
  • Nah, I need the keys and I have a condition ^^ – Raider May 21 '17 at 16:03
  • 1
    Have you attempted any code? SO is not a free coding service. You should show your attempts, or at least what you have searched/tried to address your issue. Have you even attempted using `min()` or `array_keys()`? – Sean May 21 '17 at 16:14
  • I tried a foreach loop, and some stuff with array_keys but I can't getit right – Raider May 21 '17 at 16:20
  • 1
    You should show what you tried with your `foreach loop, and some stuff with array_keys`. You could even show what your desired result would look like, based off your given criteria and sample data. – Sean May 21 '17 at 16:32

3 Answers3

4

Try this,

$arr = array_map(function($v){return $v[0];}, $graph);
$key = array_keys($arr, min($arr));
LF00
  • 27,015
  • 29
  • 156
  • 295
  • 1
    It is possible to array dereference the result of a function like this: $key = array_keys($arr, min($arr))[0]; What you think? – arbogastes May 21 '17 at 14:53
  • @arbogastes yeah, you're right. It return an array of key or keys than have the minist value. – LF00 May 21 '17 at 15:03
  • @KrisRoofe I edited the question, I'd be glad if you could help ! :) – Raider May 21 '17 at 15:54
  • you can use array_filter to filter the element have done to no. then use my code. – LF00 May 22 '17 at 02:00
0

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];
Ukasha
  • 2,238
  • 3
  • 21
  • 30
0

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
mickmackusa
  • 43,625
  • 12
  • 83
  • 136