Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
991 views
in Technique[技术] by (71.8m points)

php - How can I sort an array by number of occurrence of its values?

I have the following array:

$name_arr = array('raj','raj','ganesh','rahul','ganesh','mayur','raj','rahul');

I want to sort it like this:

$final_arr = array('raj','raj','raj','ganesh','ganesh','rahul','rahul','mayur');

How can I achieve it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Simple way using array_count_values and arsort:-

$array = array_count_values($name_arr); //get all occurrences of each values
arsort($array);
print_r($array);//print occurrences array
$final_array = array();

foreach($array as $key=>$val){ // iterate over occurrences array
  for($i=0;$i<$val;$i++){ //apply loop based on occurrences number
    $final_array[] = $key; // assign same name to the final array
  }
}

print_r($final_array); // print final array

Output:- https://eval.in/847428


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...