drecy22400 2018-12-24 14:43 采纳率: 0%
浏览 30
已采纳

如何通过前缀分隔php数组项

I want to separate a PHP array when they have a common prefix.

$data = ['status.1', 'status.2', 'status.3',
         'country.244', 'country.24', 'country.845',
         'pm.4', 'pm.9', 'pm.6'];

I want each of them in separate variables like $status, $countries, $pms which will contain:

$status = [1,2,3];
$country = [244, 24, 845]
$pms = [4,9,6]

My Current code is taking 1.5 seconds to group them:

$statuses = [];
$countries = [];
$pms = [];
$start = microtime(true);
foreach($data as $item){
    if(strpos($item, 'status.') !== false){
        $statuses[]= substr($item,7);
    }

    if(strpos($item, 'country.') !== false){
        $countries[]= substr($item,8);
    }

    if(strpos($item, 'pm.') !== false){
        $pms[]= substr($item,3);
    }
}
$time_elapsed_secs = microtime(true) - $start;
print_r($time_elapsed_secs);

I want to know if is there any faster way to do this

  • 写回答

6条回答 默认 最新

  • douyingzhan5905 2018-12-24 14:51
    关注

    This will give you results for more dynamic prefixs - first explode with the delimiter and then insert by the key to result array.

    For separating the value you can use: extract

    Consider the following code:

    $data = array('status.1','status.2','status.3', 'country.244', 'country.24', 'country.845', 'pm.4','pm.9', 'pm.6');
    
    $res = array();
    foreach($data as $elem) {
        list($key,$val) = explode(".", $elem, 2);
        if (array_key_exists($key, $res))
            $res[$key][] = $val;
        else $res[$key] = array($val);
    
    }
    extract($res); // this will seperate to var with the prefix name
    
    echo "Status is: " . print_r($status); // will output array of ["1","2","3"]
    

    This snippet took less the 0.001 second...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里