duanhun3273 2016-06-04 09:48
浏览 36

如何将数组与子元素合并

I have an array with same customerid. I want to merge all same customerid arrays in to one with few amends to the array.

Array
(
    [0] => Array
        (
            [customerid] => 13
            [customer_fullname] => Chris
            [profession_id] => 8
            [profession_name] => Producer
         )

    [1] => Array
        (
            [customerid] => 1
            [customer_fullname] => John
            [profession_id] => 8
            [profession_name] => Producer

        )

    [2] => Array
        (
            [customerid] => 13
            [customer_fullname] => Chris
            [profession_id] => 7
            [profession_name] => Camera

        )

)

So now I want a new array to be created like this:

Array(
    [customerid] => 13
    [customer_fullname] => Chris
    [new_array] => array(
        [0]=>[profession_id] => 8, [profession_name] => Producer, 
        [1]=>[profession_id] => 7, [profession_name] => Camera
    )
)

Spent some time on it but wasn't able to get it right

  • 写回答

3条回答 默认 最新

  • drblhw5731 2016-06-04 09:59
    关注

    There are better approaches if you're merging lots of records, but if you want a way to just merge two records as stated, I'd just do this:

    $array1 = array(
          'customerid' => 13
          'customer_fullname' => 'John',
          'profession_id' => 8,
          'profession_name' => 'Producer'
    );
    $array2 = array(
          'customerid' => 13
          'customer_fullname' => 'John',
          'profession_id' => 7,
          'profession_name' => 'Director'
    );
    
    function merge_customers($customerA, $customerB)
    {
        $newCustomer = array();
        if ($customerA['customerid'] == $customerB['customerid'])
        {
            $newCustomer['customerid'] = $customerA['customerid'];
            $newCustomer['customer_fullname'] = $customerA['customer_fullname'];
    
            $newCustomer['new_array'] = array(
                array(
                    'profession_id' => $customerA['profession_id'],
                    'profession_name' => $customerA['profession_name']
                ),
                array(
                    'profession_id' => $customerB['profession_id'],
                    'profession_name' => $customerB['profession_name']
                )
            );
    
            return $newCustomer;
        }
    
        /* We can't merge these if they're different customers. */
        return NULL;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?