Good day to all.

The task is as follows: by key, find the maximum value of the array and remove from the array all elements whose key is less than the maximum.

The array looks like this.

Array ( [response] => Array ( [count] => 41 [items] => Array ( [0] => Array ( [id] => 12345 [from_id] => 12345 [date] => 1480622801 [text] => Text [likes] => Array ( [count] => 0 ) ) ... 

I found a way to find the maximum value of the array -

 foreach($members['response']['items'] as $k => $val){ $array_ataj[] = $val['likes']['count']; } echo max($array_ataj); 

But at the same time, I don’t know to leave the array with the maximum value (that is, to get the keys and values ​​returned) .. I ask for help in this matter.

    2 answers 2

     $max = null; foreach($members['response']['items'] as $k => $val){ $cnt = $val['likes']['count']; if (!isset($max) || ($max < $cnt)) $max = $cnt; } // ΠŸΠ΅Ρ€Π΅Π½ΡƒΠΌΠ΅Ρ€ΠΎΠ²Ρ‹Π²Π°Π΅ΠΌ ΠΊΠ»ΡŽΡ‡ΠΈ $members['response']['items'] = array_merge($members['response']['items']); for ($i = count($members['response']['items']) - 1; $i >= 0; $i--) { if ($members['response']['items'][$i]['likes']['count'] < $max) unset($members['response']['items'][$i]) } // ΠŸΠ΅Ρ€Π΅Π½ΡƒΠΌΠ΅Ρ€ΠΎΠ²Ρ‹Π²Π°Π΅ΠΌ ΠΊΠ»ΡŽΡ‡ΠΈ $members['response']['items'] = array_merge($members['response']['items']); 
    • Thank you very much. It seems everything works. - Eva_m

    Well, of course, I didn’t really understand the essence of the question and cannot comment, but

     $max = 0; $id = array(); foreach($members['response']['items'] as $k=>$v){ if($v['likes']['count'] > $max){ $max = $v['likes']['count'];//Π‘Π½Π°Ρ‡Π°Π»Π° Π½ΡƒΠΆΠ½ΠΎ ΡƒΡΡ‚Π°Π½ΠΎΠ²ΠΈΡ‚ΡŒ максимум } } foreach($members['response']['items'] as $k=>$v){ if($v === $max){ $id[] = $k; //Π—Π°Ρ‚Π΅ΠΌ Π½Π°Ρ…ΠΎΠ΄ΠΈΠΌ всС элСмСнты ΠΊΠΎΠ»-Π²ΠΎ Π»Π°ΠΉΠΊΠΎΠ² Ρƒ ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Ρ… соотвСтствуСт максимуму } } $random_array = $members['response']['items'][array_rand($id)];//Ρ‚Π°ΠΊ получится случайная запись foreach($id as $k=>$v){//Π° Ρ‚Π°ΠΊ ΠΌΠΎΠΆΠ½ΠΎ Ρ€Π°Π±ΠΎΡ‚Π°Ρ‚ΡŒ с ΠΊΠ°ΠΆΠ΄ΠΎΠΉ $entry_id = $id[$k]; //Π½ΠΎΠΌΠ΅Ρ€ записи ΠΈΠ· $members $likes = $members['response']['items'][$entry_id][likes][count]; //количСство Π»Π°ΠΉΠΊΠΎΠ² $entry_array = $members['response']['items'][$entry_id]; //сам массив ΠΈΠ· $members } 
    • Sorry for the clumsy description. It seems almost like that, only how instead of $ id to get an array of this record - Eva_m
    • @Eva_m fixed the answer - SLy_huh
    • Thank you very much ... And the last nuance. What happens if there are 2 maximum values? - Eva_m
    • @Eva_m will be displayed last. I left it because there was no indication if there would be more than one. I paraphrase the answer - SLy_huh
    • Is it possible to deduce not the last, but the random? - Eva_m