0

I have this foreach loop and I want only take and display the array of the largest value of buildings

this is my loop

$this->TaTarVillages = array();
foreach ($this->GetTaTaRVillages() as $value) {
    $this->TaTarVillages[] = array(
        'id' => $value['id'],
        'player_id' => $value['player_id'],
        'player_name' => $value['player_name'],
        'village_name' => $value['village_name'],
        'alliance_id' => $value['alliance_id'],
        'alliance_name' => $value['alliance_name'],
        'buildings' => $this->getWonderLandLevel($value['buildings'])
    );
}

Using PHP 7

Barmar
  • 741,623
  • 53
  • 500
  • 612
HaMaDa
  • 1
  • 5
  • you might want to tag this question with the language you are using – Ian Kenney Jan 23 '22 at 00:35
  • I am using php7 as a programming language – HaMaDa Jan 23 '22 at 00:38
  • What if there is a tie for highest? Only keep the first? Do you want to potentially keep all rows with the highest value? Barmar's approach is found in [this answer](https://stackoverflow.com/a/17339754/2943403). – mickmackusa Jan 23 '22 at 03:55

1 Answers1

0

You don't need an array if you only want the largest one. Each time through the loop, check if the current value is larger than the largest one you've gotten so far, and replace it if so.

$largestVillage = $this->GetTaTaRVillages();
$largestVillage['buildings'] = $this->getWonderLandLevel($largestVillage['buildings']);
foreach ($this->GetTaTaRVillages() as $value) {
    $buildings = $this->getWonderLandLevel($value['buildings']);
    if ($buildings > $largestVillage['buildings']) {
        $largestVillage = $value;
        $largestVillage['buildings'] = $huildings;
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I got the correct result but I have errors `Notice: Undefined index: buildings in AuthController.php on line 52` `Notice: Undefined offset: 1 in AuthController.php on line 291` getWonderLandLevel function `function getWonderLandLevel($builds) { $b_arr = explode(',', $builds); $indx = 0; foreach ($b_arr as $b_str) { ++$indx; $b2 = explode(' ', $b_str); $itemId = $b2[0]; $level = $b2[1]; if ($itemId == 40) { return $level; } } return 0; }` – HaMaDa Jan 23 '22 at 10:13
  • I'm calling `getWonderLandLevel()` the same way your original code does. I assume that's correct. – Barmar Jan 23 '22 at 20:47
  • right it's worked without any errors, thank you :) – HaMaDa Jan 25 '22 at 10:29