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 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址