How to concatenate / concatenate / insert from two different arrays based on key value in PHP
I need to concatenate 2 different array types based on the same key value 1st array:
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 result:
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 array example and the result I gave. I am trying to combine 2 different arrays into 1. Array 1
is a list of numerous products, and a Array 2
is a list of the seller's name and information. I am trying to assign each product according to the seller's token.
So I am trying to combine 2 different arrays based on the key value product[name]
and seller[handle]
to create final output
as shown above
source to share
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 handle,
// add it to the result array
$result[] = array(
'name' => $product['name'],
'type' => $product['type'],
'seller' => $seller['name']);
}
}
}
source to share