示例我有这样的数组:
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => 5
[5] => 5
[6] => 5
[7] => 6
[8] => 7
[9] => 8
[10] => 9
)
我的问题是,如何创建这样的新数组。因此,为相同的值创建新数组:
Array
(
[0] => Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
)
[1] => Array
(
[0] => 5
[1] => 5
[2] => 5
)
[2] => 6
[3] => 7
[4] => 8
[5] => 9
)
请帮助我和我的坏英语。
答案 0 :(得分:2)
$result = [];
foreach (array_count_values($array) as $value => $occurrences) {
$result[] = $occurrences == 1 ? $value : array_fill(0, $occurrences, $value);
}
见http://php.net/array_count_values。事实上,这可能正是你所寻找的;我没有看到多次重复相同值的重点。
答案 1 :(得分:0)
使用array_count_values
<?php
$tr = Array(1,1,1,1,5,5,5,6,7,8,9,10);
$array= array_count_values($tr);
var_dump($array);
$arry1 = array();
foreach($array as $key =>$val){
if ($val>1){
$tmp =array();
for($i= 0;$i<$val;$i++){
$tmp[] =$key;
}
$arry1[] =$tmp;
}
else{
$arry1[] =$key;
}
}
var_dump( $arry1);
?>