当它们具有公共前缀时,我想分离一个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);
我想知道是否有更快的方法
参考方案
这将为您提供更多动态前缀的结果-首先使用定界符爆炸,然后按键插入结果数组。
要分隔值,可以使用:extract
考虑以下代码:
$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秒...
PHP strtotime困境 - php有人可以解释为什么这在我的服务器上输出为true吗?date_default_timezone_set('Europe/Bucharest'); var_dump( strtotime('29.03.2015 03:00', time()) === strtotime('29.03.2015 04:00…
PHP-全局变量的性能和内存问题 - php假设情况:我在php中运行一个复杂的站点,并且我使用了很多全局变量。我可以将变量存储在现有的全局范围内,例如$_REQUEST['userInfo'],$_REQUEST['foo']和$_REQUEST['bar']等,然后将许多不同的内容放入请求范围内(这将是适当的用法,因为这些数据指的是要求自…
php-casperjs获取内部文本 - php我正在为casperjs使用php包装器-https://github.com/alwex/php-casperjs我正在网上自动化一些重复的工作,我需要访问一个项目的innerText,但是我尚不清楚如何从casperjs浏览器访问dom。我认为在js中我会var arr = document.querySelector('label.input…
PHP-从最后一个循环中删除逗号 - php我在循环时有一个PHP,如果是最后一个循环,我想从,中删除最后一个逗号echo '],'; while($ltr = mysql_fetch_array($lt)){ echo '['; echo $ltr['days']. ' ,'. $ltr['name…
PHP Laravel从另一个驱动器读取文件 - php我目前正在学习Laravel。我想知道是否有一种方法可以在Laravel中使用Storage::从另一个硬盘访问文件(使用Windows)。例如,我在驱动器C:上安装了带有Laravel的Xampp,但是我想访问网站目录之外的E:上的文件。我试过使用Storage::files('E:')和File::files('E:…