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

标签 php arrays merge

我需要根据相同的键值合并两种不同类型的数组 第一个数组:

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
 }
}

第二个数组:

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

最终输出:

 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
     }
    }

从示例数组和我给出的输出来看。我正在尝试将 2 个不同的数组合并为 1 个。数组 1 是众多产品的列表,而数组 2 是卖家名称和信息的列表。我正在尝试根据卖家句柄分配每个产品。

因此,我尝试根据 product[name]seller[handle] 键值合并 2 个不同的数组,以生成最终输出 如上所示

最佳答案

这是一个非常标准的方法:

$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']);
        }
    }
}

关于php - 如何根据 PHP 中的键值合并/组合/插入 2 个不同的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31236910/

相关文章:

java - 适合电子医疗系统的工具和技术?

javascript - 展平深度嵌套的对象数组

Java:混合两个 WAV 文件而不引入噪音

git - 什么是 merge 冲突?

PHP fatal error 。 empty() 是否试图改变传递给它的结果?

php - 在 php 和 mySQL 中将 DATE 转换为 DATETIME

php - 从 mysql 表匹配 json 数组

javascript - 弹出对话框数值重复

c++ - Big-O 用于二维数组和链表

visual-sourcesafe - 项目级别的 SourceSafe 合并