首页 > 解决方案 > 如何通过前缀分隔php数组项

问题描述

当 PHP 数组有一个共同的前缀时,我想将它们分开。

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

我希望它们中的每一个$status, $countries, $pms都包含在单独的变量中,例如:

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

我当前的代码需要 1.5 秒来对它们进行分组:

$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);

我想知道是否有更快的方法来做到这一点

标签: phparrays

解决方案


这将为您提供更多动态前缀的结果 - 首先使用分隔符展开,然后通过键插入结果数组。

为了分离可以使用的值:提取

考虑以下代码:

$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"]

这个片段花费了更少的 0.001 秒......


推荐阅读