简体   繁体   English

如何根据PHP中的键值合并/组合/插入2个不同的数组

[英]How to merge/combine/insert of 2 different arrays based on key value in PHP

I need to merge 2 different kinds of array based on the same key value 1st Array:我需要基于相同的键值 1st Array 合并 2 种不同类型的数组:

Array{
 [0]=>Product{
  [name]=>car
  [type]=>honda
 }
 [1]=>Product{
  [name]=>motorbike
  [type]=>suzuki
 }
 [2]=>Product{
  [name]=>superbike
  [type]=>audi
 }
[3]=>Product{
  [name]=>car
  [type]=>suzuki
 }
}

2nd Array:第二个阵列:

Array{
 [0]=>Seller{
  [name]=>andy
  [handle] =>car
 }
 [1]=>Seller{
  [name]=>davies
  [handle] =>superbike
 }
 [2]=>Seller{
  [name]=>kevin
  [handle] =>motorbike
 }
}

Final Output:最终输出:

 Array{
     [0]=>Product{
      [name]=>car
      [type]=>honda
      [seller]=>kevin
     }
     [1]=>Product{
      [name]=>motorbike
      [type]=>suzuki
      [seller]=>kevin
     }
     [2]=>Product{
      [name]=>superbike
      [type]=>audi
      [seller]=>davies
     }
    [3]=>Product{
      [name]=>car
      [type]=>suzuki
      [seller]=>andy
     }
    }

So from the example array and the output that i given.所以从示例数组和我给出的输出。 I m trying to merge 2 different arrays into 1. Array 1 is the list of numerous product while Array 2 is the list of seller name and info.我正在尝试将 2 个不同的数组合并为 1。 Array 1是众多产品的列表,而Array 2是卖家名称和信息的列表。 I m trying to assign each product according to the seller handle.我正在尝试根据卖家句柄分配每个产品。

Therefore im trying to merge 2 different arrays based on the key value which is product[name] and seller[handle] to produce the final output as shown above因此,我尝试根据product[name]seller[handle]的键值合并 2 个不同的数组,以产生如上所示的final output

Here's a pretty standard approach:这是一个非常标准的方法:

$result = array();

foreach ($sellers as $seller) {
    // For each seller, loop through products and 
    // check if the name matches the sellers handle
    foreach ($products as $product) {
        if ($product['name'] == $seller['handle']) {
            // When a product has a name that matches the seller's handle, 
            // add it to the result array 
            $result[] = array(
                'name' => $product['name'], 
                'type' => $product['type'], 
                'seller' => $seller['name']);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM