PHP: En çok kullanılan dizi anahtarı bulmak nasıl?

2 Cevap php

Ben 10-20 girişleri ile basit bir 1D dizi var diyelim. Bazı nasıl en çok kullanılan hangi giriş öğrenmek istiyorsunuz, yinelenen olacak? gibi ..

$code = Array("test" , "cat" , "test" , "this", "that", "then");

Nasıl "test" en çok kullanılan giriş olarak gösterecektir?

2 Cevap

Sen array_count_values kullanarak her değer oluşum sayısı bir sayı alabilirsiniz.

$code = array("test" , "cat" , "cat", "test" , "this", "that", "then");
$counts = array_count_values($code);
var_dump($counts);
/*
array(5) {
  ["test"]=>
  int(2)
  ["cat"]=>
  int(2)
  ["this"]=>
  int(1)
  ["that"]=>
  int(1)
  ["then"]=>
  int(1)
}
*/

En sık rastlanan değeri elde etmek için, dizide max aramak ve ardından array_search ile (ilk) değeri erişebilirsiniz.

$code = array("test" , "cat" , "cat", "test" , "this", "that", "then");
$counts = array_count_values($code);
$max = max($counts);
$top = array_search($max, $counts);
var_dump($max, $top);
/*
int(2)
string(4) "test"
*/

Birden, en sık görülen değerlere hitap etmek istiyorsanız, o zaman aşağıdaki gibi bir şey çalışmak:

$code = array("test" , "cat" , "cat", "test" , "this", "that", "then");
$counts = array_count_values($code);
$max = max($counts);
$top = array_keys($counts, $max);
var_dump($max, $top);
/*
int(2)
array(2) {
  [0]=>
  string(4) "test"
  [1]=>
  string(3) "cat"
}
*/