duanmiyang6201 2016-03-18 19:54
浏览 97

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

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. 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; 
           } 
       } 
}
  • 写回答

2条回答 默认 最新

  • dourang6423 2016-03-18 20:20
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c