我有一个数组:
[ 0 ] => 3000mAh battery
[ 1 ] => charges 1 smartphone
[ 2 ] => input: 5W (5V, 1A) micro USB port
[ 3 ] => output: Micro USB cable: 7.5W (5V, 1.5A)
[ 4 ] => recharge time 3-4 hours
[ 5 ] => includes Micro USB cable
[ 6 ] => 1-Year Limited Warranty我希望删除这些键,并将字符串中已经值的部分放入其中。我想要的最终结果是:
[ battery ] => 3000mAh
[ charges ] => 1 smartphone
[ input ] => 5W (5V, 1A) micro USB port
[ output ] => Micro USB cable: 7.5W (5V, 1.5A)
[ recharge ] => time 3-4 hours
[ includes ] => Micro USB cable
[ Warranty ] => 1-Year Limited 这里有三个条件:
1)如果字符串有:那么将文本放在前面:并将其放在关键示例中:
[ 2 ] => input: 5W (5V, 1A) micro USB port
[ input ] => 5W (5V, 1A) micro USB port2)如果字符串以数字开头,取字符串的最后一个字,并将其放在键上:
[ 0 ] => 3000mAh battery
[ battery ] => 3000mAh 3)如果字符串以字母开头,取字符串的第一个单词,并将其放在键上:
[ 1 ] => charges 1 smartphone
[ charges ] => 1 smartphone这是我的代码,解决了第一个条件,你能帮我做好剩下的吗?
$new_array= array_reduce($old_array, function ($c, $v){
preg_match('/^([^:]+):\s+(.*)$/', $v, $m);
if(!empty($m[1])){
return array_merge($c, array($m[1] => $m[2]));}
else{
return array();
}
},[]);发布于 2018-11-28 20:26:40
而不是使用regexes -仅仅使用explode()可以更快更清楚地分解项目(IMHO)。这首先看起来是用:来分割它,如果这会产生一个结果,那么使用第一个条目作为键,其余的作为内容。如果失败,那么使用空格并检查使用哪个版本(在第一个字符上使用is_numeric() ).
$output = [];
foreach ( $data as $item ) {
$split = explode(":", $item );
if ( count($split) > 1 ) {
$key = array_shift($split);
$join = ":";
}
else {
$split = explode(" ", $item);
if ( strtolower($split[count($split)-1]) == "warranty" ||
is_numeric($item[0]) ){
$key = array_pop($split);
}
else {
$key = array_shift($split);
}
$join = " ";
}
$output[$key] = implode($join, $split);
}
print_r($output);发布于 2018-11-28 20:30:51
您可以使用alpha或数字检查第一个字符。要检查是否有:,可以使用greater,并检查计数是否大于1。
要编写值,可以使用带有空格的内爆作为粘合剂。
$result = [];
foreach ($items as $item) {
$res = explode(':', $item);
if (count($res) > 1) {
$key = $res[0];
array_shift($res);
$result[$key] = implode(':', $res);
continue;
}
if (is_numeric($item[0])) {
$parts = (explode(' ', $item));
$key = array_pop($parts);
$result[$key] = implode(' ', $parts);
continue;
}
if (ctype_alpha ($item[0])) {
$parts = explode(' ', $item);
$key = array_shift($parts);
$result[$key] = implode(' ', $parts);
}
}
print_r($result);https://stackoverflow.com/questions/53527279
复制相似问题