dousong2023 2014-11-25 09:25
浏览 36
已采纳

PHP将来自另一个关联数组的元素附加到具有相同键的相同数组中

I have a few associative arrays and I would like to combine them into one associative array. For example:

$array_1 = Array 
( 
    [0] => Array ( [user_id] => 111 [first_name] => Jack [last_name] => Scotts [email] )
    [1] => Array ( [user_id] => 222 [first_name] => David [last_name] => Weathers [email] )
    [2] => Array ( [user_id] => 333 [first_name] => Helen [last_name] => Reynolds [email] )
)

$array_2 = Array 
( 
    [111] => Array 
    ( 
        [0] => Array([user_account] => 111_001 [account_type] => normal ) 
        [1] => Array([user_account] => 111_002 [account_type] => vip )
    )

    [222] => Array 
    ( 
        [0]=> Array([user_account] => 222_01 [account_type] => normal ) 
    )
    [333] => Array 
    ( 
        [0]=> Array([user_account] => 333_01[account_type] => vip )
    )
)


Results:
$new_array = Array 
( 
    [0] => Array 
    ( 
        [user_id] => 111 
        [first_name] => Jack 
        [last_name] => Scotts 
        [account_data] = > Array 
        ( 
            [0] => Array([user_account] => 111_001 [account_type] => normal ) 
            [1] => Array([user_account] => 111_002 [account_type] => vip )
         )
    )
    [1] => Array 
    ( 
        [user_id] => 222 
        [first_name] => David 
        [last_name] => Weathers
        [account_data] => Array 
        ( 
            [0]=> Array([user_account] => 222_01 [account_type] => normal ) 
        )
     )
    [2] => Array 
    ( 
        [user_id] => 333 
        [first_name] => Helen 
        [last_name] => Reynolds 
        [account_data] => Array
        (
            [0] => Array ( [user_account] => 333_01 [account_type] => vip )
        )
    )
)

Tried both array_merge and array_merge recursive but it doesn't work.

  • 写回答

2条回答 默认 最新

  • dongshangan2074 2014-11-25 09:38
    关注

    There is no native PHP functionality for this, since this is not a very standard way of merging arrays together. You can write a loop that will do it for you though, using foreach():

    $new_array = [];
    
    foreach($array_1 as $user){
        $temp = $user;
        $temp['account_data'] = $array_2[$user['user_id']];
        $new_array[] = $temp;
    }
    

    Demo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀