Ananda Pramono
Ananda Pramono

Reputation: 1009

Count duplicate data and store it to a variable

I want to count the duplicated data in an array and store it to a variable. I managed to count it using array_count_values() but I dont know how to store it to a variabel. I tried to access the array from 'array_count_values()' but it give an error with Undefined offset

Here is my controller

 $query  = DB::table("detiltransaksiservice")->leftJoin('service', 'service.kodeService', 'detiltransaksiservice.kodeService')
    ->select('service.keterangan')->get();
    $count  = count($query);
    $kode   = [];
    $query = $query->toArray();
    for($i=0;$i<$count;$i++)
    {
        $kode[$i] = $query[$i]->keterangan;
    }
    $test = array_count_values($kode);
    dd($test[0]);

And here is the array_count_values()

enter image description here

I want to store the biggest number from array_count_values(), in my case its 2 and Service Stang a different variable. Hope you can help me. Thanks

Upvotes: 0

Views: 72

Answers (3)

Rahul
Rahul

Reputation: 18577

You can use collection helper to achieve this\

$filtered = $query->filter(function ($value, $key) {
    return $value > 1;
});

Here is the official documentation of it.

Note: Recommended to use before $query = $query->toArray(); line.

Upvotes: 2

namelivia
namelivia

Reputation: 2745

You can also do this:

$query  = DB::table("detiltransaksiservice")
    ->leftJoin(
        'service',
        'service.kodeService',
        'detiltransaksiservice.kodeService'
    )
    ->select('service.keterangan')->get();

$test = $query->filter(
    function ($item) {
        return $item->keterangan === 'Service Stang';
    }
)->count();

Upvotes: 2

Qirel
Qirel

Reputation: 26490

A probably better way is to create a query that gets this result for you, by using aggregate functions COUNT() and GROUP BY with HAVING COUNT(*) > 1.

$result = DB::table("detiltransaksiservice")->leftJoin('service', 'service.kodeService', 'detiltransaksiservice.kodeService')
    ->select('service.keterangan', DB::raw('COUNT(*) as total'))
    ->groupBy('service.keterangan')
    ->havingRaw("COUNT(*) > 1")
    ->get();

If you however want to do it in PHP, you can use array_filter().

You can filter the result from array_count_values() by counts greater than one. Given that it could theoretically be more than one entry that has more than two occurrences, it would be best to keep it as an indexed array.

$array = ['Service Mesin Ringan' => 1, 'Service Stang' => 2, 'Service Kabel' => 1];
$array = array_filter($array, function($v) { return $v > 1; });
var_dump($array);

Output:

array(1) {
  ["Service Stang"]=>
  int(2)
}

Upvotes: 2

Related Questions