我有2个阵列
数组1:Array ( [0] => Merc [1] => # [2] => BM [3] => & [4] => Lotus )
阵列2:Array ( [0] => 6740 [1] => 4565 [2] => 3423 )
目标是组合2个数组,最后得到:
$result = ['Merc' => 6740, 'BM' => 4565, 'Lotus' => 3423];
我已经知道了相当多的指导,我已经阅读了它,但数组操作对我来说是新的,不知何故我无法理解逻辑和语法。
有经验的人可以告诉我哪里出错了。
我试过了:
...
//// lets echo the arrays to make sure they are correct
print_r($car);?><br><?php
print_r($part);?><br><?php
//// lets combine the 2 arrays to get an associative array
$result = [];
for($i = 0; $i < count($car); $i++){
if (($car[$i] == "&")||($car[$i] == "#")){
$i = ($i + 1);
}
foreach($car as $car) {
foreach($part as $part) {
$result[] = array(
$car => $part,
);
}
}
}
print_r($result);
这个输出是:
Array ( [0] => Array ( [Merc] => 6740 ) [1] => Array ( [BM] => 4565 ) [2] => Array ( [Lotus] => 3423 ))
要删除的特殊字符只能是#
或&
答案 0 :(得分:3)
过滤掉不需要的元素并将它们合并。
代码:(Demo)
$cars=['Merc','#','BM','&','Lotus'];
$parts=[6740,4565,3423];
$cars=array_diff($cars,['#','&']);
var_export(array_combine($cars,$parts));
输出:
array (
'Merc' => 6740,
'BM' => 4565,
'Lotus' => 3423,
)
P.S。您也可以使用ctype_alpha()进行过滤:(Demo)
$cars=array_filter($cars,'ctype_alpha'); // only retain elements that are fully comprised of letters