0

I can achieve this easily enough with loops, but it seems messy and I wondered if there's something that could be done with array_map or similar?

Given the following array:

[1]=>
array(3) {
  ["foo"]=>
  int(25)
  ["bar"]=>
  int(100)
  ["total"]=>
  int(125)
}
[2]=>
array(3) {
  ["foo"]=>
  int(11)
  ["bar"]=>
  int(38)
  ["total"]=>
  int(49)
}
[3]=>
array(3) {
  ["foo"]=>
  int(20)
  ["bar"]=>
  int(100)
  ["total"]=>
  int(120)
}

How would you go about flagging the index with the lowest total?

e.g. to change it to:

[1]=>
array(3) {
  ["foo"]=>
  int(25)
  ["bar"]=>
  int(100)
  ["total"]=>
  int(125)
}
[2]=>
array(4) {
  ["foo"]=>
  int(11)
  ["bar"]=>
  int(38)
  ["total"]=>
  int(49)
  ["lowest"]=>
  bool(true)
}
[3]=>
array(3) {
  ["foo"]=>
  int(20)
  ["bar"]=>
  int(100)
  ["total"]=>
  int(120)
}

(adding "lowest" => false to the other indexes is unnecessary but acceptable)

Many thanks, I can't get my head around it. My brain seems to be failing me, it's been a long day.

1
  • 2
    loops will be involved no matter what Commented Sep 21, 2016 at 22:12

1 Answer 1

3

Using array_column() we can retrieve subarray. Then using min() find the lowest value and find corresponding key using array_search():

$total = array_combine(array_keys($array), array_column($array, 'total'));
$minKey = array_search(min($total), $total);
$array[$minKey]['lowest'] = true;

To preserve original keys here's also combination of array_keys() and array_combine()

Sign up to request clarification or add additional context in comments.

2 Comments

Except array_column() will return a 0 based array. So the search will return index 1 but in the original array the minimum is at index 2.
Thanks! To my eye it's not super obvious code so I'll probably stick with a loop as at least that's easy to read/understand, but I learnt something here :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.