PHP 如何将一个关联的数组键替换为另一个数组值


PHP How to replace one associative array keys with another array values

我有两个数组,我需要第一个数组的值成为关联数组每一行的键。我想我说得对。我有两个数组:

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; 
           } 
       } 
}

此脚本:

    $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);

给你你想要的。

实际上,我们只是丢弃密钥并依赖于这些项目的顺序。

这里 - 没有foreach :)

$result = array_map(
    function($person) use ($keys) { 
        return array_combine($keys, $person);
    },
    $source);

http://sandbox.onlinephpfunctions.com/code/68fe2c199ac47349d5391b6b87bef7779cd945ad