我有一个包含多个数组的数组,如
$A = array();
$A[0] = array("1","2","3","4","5");
$A[1] = array("1","6","7","8");
$A[2] = array("0","1","3");
我想按频率顺序对多个数组中的值进行排序,并将它们放入另一个数组中,假设为$ B.
$ B中的值为“1”,“1”,“1”,“3”,“3”,“0”,“2”,“4”,“5”,“6”,“ 7" , “8”。
答案 0 :(得分:2)
$A = array();
$A[0] = array("1","2","3","4","5");
$A[1] = array("1","6","7","8");
$A[2] = array("0","1","3");
//Merging above array in to one array
$merged = array_values(call_user_func_array('array_merge', $A));
//Getting occurrence count
$counts = array_count_values($merged);
//Sort by count
arsort($counts);
//Adding to required array
$B = array();
foreach ($counts as $k => $v)
for($i=1;$i<=$v;$i++)
$B[] = $k;
echo "<pre>";
print_r($B);
echo "</pre>";
<强>结果强>
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 3
[4] => 3
[5] => 0
[6] => 8
[7] => 7
[8] => 5
[9] => 2
[10] => 4
[11] => 6
)
答案 1 :(得分:0)
首先合并所有数组
$ array1 = array(“color”=&gt;“red”,2,4);
$ array2 = array(“a”,“b”,“color”=&gt;“green”,“shape”=&gt;“trapezoid”,4);
$ resultado = array_merge($ array1,$ array2);
参见 - &gt; http://php.net/manual/es/function.array-merge.php
第二次排序大数组
arsort($ resultado);
答案 2 :(得分:0)
使用哈希表计算每个数字的频率,然后按照数组$B
中频率的降序存储它们,如下所示:
$hash_table = array();
foreach($A as $array){
foreach($array as $value){
if(empty($hash_table[$value])){
$hash_table[$value] = 1;
}else{
$hash_table[$value] += 1;
}
}
}
arsort($hash_table);
$B = array();
foreach($hash_table as $key => $value){
for($i = 0; $i < $value; ++$i){
$B[] = $key;
}
}
var_dump($B); // to see the contents of array $B
答案 3 :(得分:0)
如果相同的出现计数项目的顺序不重要,您可以使用:
// Merge all arrays
$counts = array_count_values(call_user_func_array('array_merge', $A));
// Sort by occurance
arsort($counts);
// Add [value] to new array [occurance] times
$B = array();
array_walk($counts, function($occurances, $value) use (&$B){
for($i=0;$i<$occurances;$i++) $B[] = $value;
});
echo implode(',', $B);
<强>输出强>
1,1,1,3,3,0,8,7,5,2,4,6
答案 4 :(得分:0)
if (haveNetworkConnection()) {
new androidTask().execute();
} else {
Toast.makeText(context, "No Network Connection", Toast.LENGTH_SHORT).show();
}