Reputation: 87
Example I have array like this:
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 1
[4] => 5
[5] => 5
[6] => 5
[7] => 6
[8] => 7
[9] => 8
[10] => 9
)
And my question is, how to create new array like this. So create new array for the same value:
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
)
Please help me and sory for my bad english.
Upvotes: 1
Views: 87
Reputation: 1146
Try this one using 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);
?>
Upvotes: 0
Reputation: 522042
$result = [];
foreach (array_count_values($array) as $value => $occurrences) {
$result[] = $occurrences == 1 ? $value : array_fill(0, $occurrences, $value);
}
See http://php.net/array_count_values. In fact, this may really be what you're looking for; I don't see the point in repeating the same value many times.
Upvotes: 2