dowaw80220 2017-11-27 12:09
浏览 22
已采纳

分组元素数组基于php的第一个字符值

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
]

Please advise

  • 写回答

3条回答 默认 最新

  • drctyr2869 2017-11-27 13:04
    关注

    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,
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路