Php 用于更改数组中键值的模式
我有一个数组:Php 用于更改数组中键值的模式,php,arrays,Php,Arrays,我有一个数组: [ 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 ] =&g
[ 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) 若字符串以数字开头,则取字符串的最后一个字,并将其像键一样放置:
[ 0 ] => 3000mAh battery
[ battery ] => 3000mAh
[ 1 ] => charges 1 smartphone
[ charges ] => 1 smartphone
3) 如果字符串以字母开头,则取字符串的第一个单词,并将其像键一样放置:
[ 0 ] => 3000mAh battery
[ battery ] => 3000mAh
[ 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();
}
},[]);
不要使用正则表达式-只需使用
explode()
就可以更快更清晰地分解项目。首先用:
将其拆分,如果这会产生一个结果,则使用第一个项作为键,其余项作为内容。如果失败,则使用空格并检查要使用的版本(在第一个字符上使用is\u numeric()
)
您可以使用或检查第一个字符。要检查
:
,可以使用explode并检查计数是否大于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);
在第一个
if()
中,您使用:
分割文本,然后使用“`”(一个空格)内爆,这将从文本中删除任何:
(如微型USB电缆:7.5W(5V,1.5A)
)。还有,为什么要使用continue
而不是elseif
?@NigelRen没错,应该是:
。非常感谢。我使用continue
,因为我觉得如果没有elseif
,它更容易阅读。但是你也可以用elseif
来写,当然这很好!但在某些情况下,我还需要一个条件。若字符串以字母开头,且该字符串中有单词warranty,则将单词warranty作为键name@doki您可以这样做,但请注意哪些阵列不能具有相同的密钥,因此,如果保修在多行中,则无法工作。此解决方案只需第一次出现保修。这太棒了!但在某些情况下,我还需要一个条件。如果字符串以字母开头,并且字符串中是单词“保修”,请将单词“保修”作为关键字名称。您能否给出一个实际文本的示例,以及您希望从中得到什么。终身保修使用此代码,它会将单词“终身保修”作为关键字,但保修必须始终是关键字我已更新了代码-以if(strtolower($split[0]开头的行))==“保修”){
检查下一个单词是否为保修,并将其添加到已提取的第一个单词中