简体   繁体   English

PHP如何用另一个数组值替换一个关联数组键

[英]PHP How to replace one associative array keys with another array values

I have two arrays and I need the value from the first one to become the key for each row of an associative array. 我有两个数组,我需要第一个数组的值成为关联数组每一行的键。 I think I stated that correctly. 我想我说的没错。 I have two arrays: 我有两个数组:

Array
(
    [field_name0] => first_name
    [field_name1] => mobile
    [field_name2] => email
    [field_name3] => last_name
)

and

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
    )

)

I need the values from the first array to replace the values in each of the second arrays to look like this: 我需要第一个数组中的值来替换每个第二个数组中的值,如下所示:

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
    )

)

I have tried some bad attempts at some foreach loops to accomplish this but it's getting a bit tricky for me. 我在一些foreach循环中尝试了一些不好的尝试来完成此操作,但对我来说有点棘手。 Please help. 请帮忙。 I am hoping I just overlooked a simple way to do this. 我希望我只是忽略了执行此操作的简单方法。

What I tried:- 我试过的

foreach( $field_map as $origKey => $value ){ 
      foreach($csvdata as $csvrow){ 
           foreach($csvrow as $cKey => $cValue){ 
                  $newKey = $value; 
                  $newArray[$newKey] = $cValue; 
           } 
       } 
}

This script: 该脚本:

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

Gives you what you wanted. 给您您想要的。

Effectively we just discarding keys and relying on the sequence of those items. 实际上,我们只是丢弃密钥并依靠这些项目的顺序。

Here - without foreach :) 这里-没有foreach :)

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM