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条)

报告相同问题?

悬赏问题

  • ¥20 simulink中怎么使用solve函数?
  • ¥30 dspbuilder中使用signalcompiler时报错Error during compilation: Fitter failed,求解决办法
  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题