我有这个:
$Array1 = "FirstName, LastName, Email";
$Array2 = "John, Doe, johndoe@email.com";
使用foreach或其他方法,最终的数组格式可以看起来像这样吗?
$mergedArrays = array(
'FirstName' =>"John",
'LastName' => "Doe",
'Email' =>'johndoe@email.com',
);
print_r($mergedArrays);
答案 0 :(得分:3)
如果您确定两个数组都包含相同的数字(用逗号分隔),请使用以下方法:
版本1(使用100000进行测试需要〜0.08s,快+ -4倍)
<?php
$Array1 = "FirstName, LastName, Email";
$Array2 = "John, Doe, johndoe@email.com";
$Array1 = explode(',', preg_replace('/\s*,\s*/',',',$Array1)); //remove spaces before and after comma
$Array2 = explode(',', preg_replace('/\s*,\s*/',',',$Array2));
if(count($Array1) == count($Array2)) {
$result = array_combine($Array1, $Array2);
}
print_r($result);
输出:
Array (
[FirstName] => John
[LastName] => Doe
[Email] => johndoe@email.com
)
@castis的替代版本(使用100000进行测试大约需要0.3s)
$Array1 = explode(',',$Array1);
$Array2 = explode(',',$Array2);
$result = array_combine(array_map('trim', $Array1), array_map('trim', $Array2));
答案 1 :(得分:1)
如果必须使用foreach(array_combine可以在其中使用):
<?php
$fields = ['FirstName', 'LastName', 'Email'];
$values = ['John', 'Doe', 'johndoe@email.com'];
foreach($fields as $k => $field)
$result[$field] = $values[$k];
var_export($result);
输出:
array (
'FirstName' => 'John',
'LastName' => 'Doe',
'Email' => 'johndoe@email.com',
)