duanquan4451 2013-06-13 09:32
浏览 34
已采纳

数组合并递归php

Can anyone tell me how i can convert the first array to second array using php array operations.

First array :-

Array
(
    [0] => Array
        (
            [actual_release_date] => 2013-06-07 00:00:00
            [distributors] => 20th Century Fox / 20th Century Fox Animation / Fox 2000 Pictures / Fox Searchlight
        )

    [1] => Array
        (
            [actual_release_date] => 2013-06-28 11:11:00
            [distributors] => 20th Century Fox / 20th Century Fox Animation / Fox 2000 Pictures / Fox Searchlight
        )
)

Second array:-

Array
(
    [0] => Array
        (
            [actual_release_date] => array( 0=>2013-06-07 00:00:00 , 1=> 2013-06-28 11:11:00 )
            [distributors] => 20th Century Fox / 20th Century Fox Animation / Fox 2000 Pictures / Fox Searchlight
        )
)

If the second element is common, and first element is different, then we have to group it in one array.

Thanks in advance.

  • 写回答

2条回答 默认 最新

  • dongsha9208 2013-06-13 09:41
    关注

    You can use array_reduce

    $data = array_reduce($data, function ($a, $b) {
        if (isset($a[$b['distributors']])) {
            $a[$b['distributors']]['actual_release_date'][] = $b['actual_release_date'];
        } else {
            $a[$b['distributors']]['actual_release_date'] = array($b['actual_release_date']);
            $a[$b['distributors']]['distributors'] = $b['distributors'];
        }
        return $a;
    }, array());
    
    print_r(array_values($data));
    

    Output

    Array
    (
        [0] => Array
            (
                [actual_release_date] => Array
                    (
                        [0] => 2013-06-07 00:00:00
                        [1] => 2013-06-28 11:11:00
                    )
    
                [distributors] => 20th Century Fox / 20th Century Fox Animation / Fox 2000 Pictures / Fox Searchlight
            )
    
    )
    

    See Live DEMO

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

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录