Reputation: 378
I'm new in stackoverflow and it's my first question.
here's my problem.
let's say I have array like below :
$array =[1,1,1,1,2,3,3,3,3,4,5];
I'd like to filter array above so that the duplicate value (1 & 3) can be move to another array max = three time.
what I expect is :
$FilteredArray = [1,1,1,2,3,3,3,4,5];
note : 1 & 3 only move three time.
thanks in advance.
update : sorry, I forgot to mention that my array is contain an object. please refer to below :
> $array = [
> {
> "id": 3175,
> "shape_id": 307,
> "shape_pt_lat": "-6.9257591914493",
> "shape_pt_lon": "107.60664492839",
> "shape_pt_sequence": 2,
> "shape_dist_travel": "",
> "jalur": "146-147",
> "distance": 0.16133102419521
> },
> {
> "id": 3180,
> "shape_id": 308,
> "shape_pt_lat": "-6.9257591914493",
> "shape_pt_lon": "107.60664492839",
> "shape_pt_sequence": 2,
> "shape_dist_travel": "",
> "jalur": "147-146",
> "distance": 0.16133102419521
> },
> {
> "id": 3176,
> "shape_id": 307,
> "shape_pt_lat": "-6.9257911430218",
> "shape_pt_lon": "107.6069118082",
> "shape_pt_sequence": 3,
> "shape_dist_travel": "",
> "jalur": "146-147",
> "distance": 0.16415806438464
> },
> {
> "id": 3179,
> "shape_id": 308,
> "shape_pt_lat": "-6.9257911430218",
> "shape_pt_lon": "107.6069118082",
> "shape_pt_sequence": 1,
> "shape_dist_travel": "",
> "jalur": "147-146",
> "distance": 0.16415806438464
> },
> {
> "id": 3174,
> "shape_id": 307,
> "shape_pt_lat": "-6.9257312336896",
> "shape_pt_lon": "107.60638207192",
> "shape_pt_sequence": 1,
> "shape_dist_travel": "",
> "jalur": "146-147",
> "distance": 0.16421114665333
> } ]
the number 1,1,1 in array values above is the shape_id.
sorry for the unclear question.
Upvotes: 0
Views: 186
Reputation: 710
This is another way to do this using array_count_values
$array = array("1","1","1","1", "1","2","2","2","2","3","3");
$newarray = [];
for($i=0;$i<sizeof($array);$i++){
$value = $array[$i];
$counts = array_count_values($newarray);
if($counts[$array[$i]]<3){
$newarray[] = $array[$i];
}
}
print_r($newarray);
Will output
Array ( [0] => 1 [1] => 1 [2] => 1 [3] => 2 [4] => 2 [5] => 2 [6] => 3 [7] => 3 )
Upvotes: 0
Reputation: 31739
This should help -
$array =[1,1,1,1,2,3,3,3,3,4,5];
// Get unique values
$unique = array_unique($array);
// array with all values as keys to calculate occurrence
$value_count = array_combine($unique, array_fill(0, count($unique), 0));
foreach($array as $key => $value) {
// Check if occurrence reached the limit & do process
if(isset($value_count[$value]) && $value_count[$value] >= 3) {
unset($array[$key]);
} else {
// increment count
$value_count[$value] += 1;
}
}
var_dump($array);
Output
array(9) {
[0]=>
int(1)
[1]=>
int(1)
[2]=>
int(1)
[4]=>
int(2)
[5]=>
int(3)
[6]=>
int(3)
[7]=>
int(3)
[9]=>
int(4)
[10]=>
int(5)
}
Upvotes: 1