• php将两个数组相同的key合并到一个数组


    php将两个数组相同的key合并到一个数组

    $arr = array(
        array(
        'id' => 1,
        'user_name'=>'test1'
        ),
        array(
        'id' => 2,
        'user_name'=>'test2'
        ),
        array(
        'id' => 3,
        'user_name'=>'test3'
        )
    );
    $arr2 = array(
         array(
        'id' => 1,
        'shop_name'=>'shop1'
        ),
        array(
        'id' => 5,
        'shop_name'=>'shop2'
        ),
        array(
        'id' => 3,
        'shop_name'=>'shop3'
        )
    );
    怎么根据2个数组id相同的一维数组,将$arr2的shop_name添加到$arr,如果没有相同的id,shop_name为空,形成如下数组:
    $good_arr =array(
        array(
        'id' => 1,
        'user_name'=>'test1',
        'shop_name'=>'shop1'
        ),
        array(
        'id' => 2,
        'user_name'=>'test2',
        'shop_name'=>''
        ),
        array(
        'id' => 3,
        'user_name'=>'test3',
        'shop_name'=>'shop3'
        )
     
    );

    PHP5.5支持一个很棒的函数array_column()非常适合干这个事情,具体请参考手册:http://cn2.php.net/manual/zh/function.array-column.php

    
    
    $shop_name = array_column($arr2, 'shop_name', 'id');
    foreach($arr as $key => $item) {
        $exist = array_key_exists($item['id'], $shop_name);
        $arr[$key]['shop_name'] = $exist ? $shop_name[$item['id']] : '';
    }
  • 相关阅读:
    pytest_04
    pytest_03
    pytest_02
    CF 1416C XOR Trie
    CF 1413D
    ZOJ 3725 概率dp
    ZOJ 3726
    位运算
    CF1439C 线段树
    unordered_set
  • 原文地址:https://www.cnblogs.com/wrld/p/10966190.html
Copyright © 2020-2023  润新知