php - 如何通过前缀分隔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);
我想知道是否有更快的方法来做到这一点
解决方案
这将为您提供更多动态前缀的结果 - 首先使用分隔符展开,然后通过键插入结果数组。
为了分离可以使用的值:提取
考虑以下代码:
$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 秒......
推荐阅读
- node.js - 如何从 expressjs 发送 jwt 令牌以响应应用程序?
- javascript - Firebase 存储规则不允许读取或写入
- java - FXML 组合框未填充选项
- typescript - 打字稿字符串联合到元组
- python - 有没有办法阻止 youtube_dl 将其状态打印到控制台?
- python - Python MiniGame 苦苦挣扎
- c# - 实体框架 - 删除重复项
- algorithm - 当某个孩子在树上时,后购和预购?
- php - 从 Woocommerce 税收显示中删除括号
- amazon-web-services - 无法解析父 HLS 清单。- 错误代码 232600