dpl3350 2016-10-28 20:19
浏览 28
已采纳

当具有相同的特定值时,将值从一个数组添加到另一个数组

I have these two arrays:

$ar1 = array(
    0 => array(
        'name' => 'MIRIAN',
        'total' => '34'
    ),
    1 => array(
        'name' => 'THIAGO',
        'total' => '29'
    ),
    2 => array(
        'name' => 'EDUARDO',
        'total' => '3'
    )
);


$ar2 = array(
    0 => array(
        'operator' => 'THIAGO',
        'totalop' => '703'
    ),
    1 => array(
        'operator' => 'MIRIAN',
        'totalop' => '180'
    )

);

And i want to create a third like this, but i don't know what should i do:

$ar3 = array(
    0 => array(
        'name' => 'MIRIAN',
        'total' => '34'
        'totalop' => '180'

    ),
    1 => array(
        'name' => 'THIAGO',
        'total' => '29',
        'totalop' => '703'
    ),
    2 => array(
        'name' => 'EDUARDO',
        'total' => '3'
    )
);

What is the best way to do this, I tried many ways, but without success?

Thanks for any help

  • 写回答

3条回答 默认 最新

  • dongshadu4498 2016-10-28 20:32
    关注

    Solution:

    $ar1 = array(
        0 => array(
            'name' => 'MIRIAN',
            'total' => '34'
        ),
        1 => array(
            'name' => 'THIAGO',
            'total' => '29'
        ),
        2 => array(
            'name' => 'EDUARDO',
            'total' => '3'
        )
    );
    
    
    $ar2 = array(
        0 => array(
            'operator' => 'THIAGO',
            'totalop' => '703'
        ),
        1 => array(
            'operator' => 'MIRIAN',
            'totalop' => '180'
        )
    
    );
    
    
    $index = [];
    $ar1Key = 'name';
    $ar2Key = 'operator';
    
    foreach ($ar1 as $item) {
        $index[$item[$ar1Key]] = $item;
    }
    
    foreach ($ar2 as $item) {
        $pk = $item[$ar2Key];
    
        unset($item[$ar2Key]);
    
        if (isset($index[$pk])) {
            $index[$pk] = array_merge($index[$pk], $item);
        } else {
            $index[] = $item;
        }
    }
    
    $ar3 = array_values($index);
    
    print_r($ar3);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 mmseqs内存报错
  • ¥15 vika文档如何与obsidian同步
  • ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
  • ¥15 陆空双模式无人机飞控设置
  • ¥15 sentaurus lithography
  • ¥100 求抖音ck号 或者提ck教程
  • ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)
  • ¥20 web页面如何打开Outlook 365的全球离线通讯簿功能
  • ¥15 io.jsonwebtoken.security.Keys
  • ¥15 急,ubuntu安装后no caching mode page found等