我有两个数组,我需要第一个数组的值成为关联数组每一行的键。我想我说得对。我有两个数组:
Array
(
[field_name0] => first_name
[field_name1] => mobile
[field_name2] => email
[field_name3] => last_name
)
和
Array
(
[1] => Array
(
[First Name] => Peter
[mobile] => 1234567890
[email] => email@email.com
[Last Name] => Griffin
)
[2] => Array
(
[First Name] => Al
[mobile] => 9874561230
[email] => test@test.com
[Last Name] => Bundy
)
)
我需要第一个数组中的值来替换每个第二个数组中的值,如下所示:
Array
(
[1] => Array
(
[first_name] => Peter
[mobile] => 1234567890
[email] => email@email.com
[last_name] => Griffin
)
[2] => Array
(
[first_name] => Al
[mobile] => 9874561230
[email] => test@test.com
[last_name] => Bundy
)
)
我在一些foreach
循环中尝试了一些不好的尝试来实现这一点,但它对我来说有点棘手。请帮忙。我希望我忽略了一个简单的方法来做到这一点。
我尝试了什么: -
foreach( $field_map as $origKey => $value ){
foreach($csvdata as $csvrow){
foreach($csvrow as $cKey => $cValue){
$newKey = $value;
$newArray[$newKey] = $cValue;
}
}
}
答案 0 :(得分:2)
这个脚本:
$users = [
[
'First Name' => 'Peter',
'mobile' => 1234567890,
'email' => 'email@email.com',
'Last Name' => 'Griffin',
],
[
'First Name' => 'Al',
'mobile' => 9874561230,
'email' => 'test@test.com',
'Last Name' => 'Bundy',
],
];
$fields = [
'field_name0' => 'first_name',
'field_name1' => 'mobile',
'field_name2' => 'email',
'field_name3' => 'last_name',
];
$fieldNames = array_values($fields);
foreach ($users as &$user) {
$user = array_combine($fields, array_values($user));
}
print_r($users);
给你你想要的东西。
实际上,我们只是丢弃密钥并依赖这些项目的顺序。
答案 1 :(得分:0)
这里 - 没有foreach:)
$result = array_map(
function($person) use ($keys) {
return array_combine($keys, $person);
},
$source);
http://sandbox.onlinephpfunctions.com/code/68fe2c199ac47349d5391b6b87bef7779cd945ad