douzuo0002 2018-10-10 13:16
浏览 173
已采纳

从第二个数组中获取数据并将值放入数组1中

I have the following situation and cannot find an easy way to do it.

I have 2 arrays:

1)

Array (
[0] => Array
    (
        [FirstName] => Tom
        [LastName] => Siemens
        [Id] => 10300
    )

[1] => Array
    (
        [FirstName] => Sam
        [LastName] => Tailor
        [Id] => 10301
    )

2)

Array
    (
    [0] => Array
           (
            [Type] => Invoice
            [Number] => 6344394
            [Project] => Array
                (
                    [Name] => Test Project 1
                    [ResponsibleUserId] => 10300
                    [Id] => 498
                    [ResponsibleUser] => 
                )

        )
    [1] => Array (
            [Type] => Invoice
            [Number] => 6345555
            [Project] => Array
                (
                    [Name] => Test Project 2
                    [ResponsibleUserId] => 10301
                    [Id] => 499
                    [ResponsibleUser] => 
                )

        )

What could be the best approach to get the "FirstName LastName" from the first array depends on the ID which must equal the Project Id from the second array and to put these values inside the second array -> Project -> ResponsibleUser?

The result I'm looking for is the following:

Final Array)

Array (
    [0] => Array
           (
            [Type] => Invoice
            [Number] => 6344394
            [Project] => Array
                (
                    [Name] => Test Project 1
                    [ResponsibleUserId] => 10300
                    [Id] => 498
                    [ResponsibleUser] => Tom Siemens
                )

        )
    [1] => Array (
            [Type] => Invoice
            [Number] => 6345555
            [Project] => Array
                (
                    [Name] => Test Project 2
                    [ResponsibleUserId] => 10301
                    [Id] => 499
                    [ResponsibleUser] => Sam Tailor
                )

        )
  • 写回答

3条回答 默认 最新

  • dsa45132 2018-10-10 13:24
    关注

    If you start by indexing the first array by the id using array_column() ...

    $idList = array_column($array1, null, "Id");
    

    You can then just loop over the second array and pick out the name each time and update it...

    foreach (array2 as &$project ) {
        $id = $project["Project"]["ResponsibleUserId"];
        $project["Project"]["ResponsibleUser"] = $idList[$id]["FirstName"]." ".$idList[$id]["LastName"];
    }
    

    Use &$project as this allow you to update the original value which is what your after.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器