我需要根据相同的键值合并两种不同类型的数组 第一个数组:
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/