phparraysmultidimensional-arraygroupingcounting

Count the occurrences of the first character of all values in a column of a 2d array


I have an array based MySql database. This is the array.

[
  0 => [
    'id' => '1997'
    'lokasi_terakhir' => 'YA4121'
  ]
  1 => [
    'id' => '1998'
    'lokasi_terakhir' => 'PL2115'
  ]
  2 => [
    'id' => '1999'
    'lokasi_terakhir' => 'PL4111'
  ]
]

How can I get the element lokasi_terakhir that grouped by the first character ? What the best way ?

This is the goal :

[
   "Y" => 1,
   "P" => 2
]

Solution

  • Here are two refined methods. Which one you choose will come down to your personal preference (you won't find better methods).

    In the first, I am iterating the array, declaring the first character of the lokasi_terakhir value as the key in the $result declaration. If the key doesn't yet exist in the output array then it must be declared / set to 1. After it has been instantiated, it can then be incremented -- I am using "pre-incrementation".

    The second method first maps a new array using the first character of the lokasi_terakhir value from each subarray, then counts each occurrence of each letter.

    (Demonstrations Link)

    Method #1: (foreach)

    foreach($array as $item){
        if(!isset($result[$item['lokasi_terakhir'][0]])){
            $result[$item['lokasi_terakhir'][0]]=1;  // instantiate
        }else{
            ++$result[$item['lokasi_terakhir'][0]];  // increment
        }
    }
    var_export($result);
    

    Method #2: (functional)

    var_export(array_count_values(array_map(function($a){return $a['lokasi_terakhir'][0];},$array)));
    // generate array of single-character elements, then count occurrences
    

    Output: (from either)

    array (
      'Y' => 1,
      'P' => 2,
    )