I have two arrays one contains ids that's going to check if it exists on the second array which is an associative array:
Array 1: [1,2,11, 4]
Array 2:
[["id" => 1, "name" => "abc"], ["id" => 2, "name"=> "xyz"]]
Currently using a nested foreach to iterate over and match them but I wanted to know if there was anything more efficient as the arrays will be a lot larger.
$item = [1,2,11, 4];
$data = [["id" => 1, "name" => "abc"], ["id" => 2, "name"=> "xyz"]];
foreach($items as $item)
{
foreach($data as $key => $products)
{
foreach($products as $product)
{
if($product['id'] == $item)
{
echo $product['name'];
}
}
}
}
Had a look at this and this but none really fit my scenario.
Any help appreciated.
CodePudding user response:
array_filter would be an option:
$ids = [ 1, 2, 11, 4 ];
$data = [ [ 'id' => 1, 'name' => 'abc' ], [ 'id' => 2, 'name' => 'xyz' ], [ 'id' => 3, 'name' => 'nono' ] ];
$result = array_filter($data, fn($value) => (in_array($value['id'], $ids)));
CodePudding user response:
You can use array_column() to get all product ids as an indexed array.
Then you can use array_intersect() to fetch the id's that exists in both arrays.
$item = [1,2,11, 4];
$products = [["id" => 1, "name" => "abc"], ["id" => 2, "name"=> "xyz"]];
// Get the ids of all products as an indexed array
$prodIds = array_column($products, 'id');
// Check the id's that exists in both
$existingIds = array_intersect($item, $prodIds);
Demo: https://3v4l.org/HJSoq
Of if you rather do it as a one-liner:
$existingIds = array_intersect($item, array_column($products, 'id'));
CodePudding user response:
You can also use the array_map and the anonymous function.
$item = [1, 2, 11, 4];
$products = [["id" => 1, "name" => "abc"], ["id" => 2, "name" => "xyz"]];
$result = array_map(function ($row) use ($item) {
return (in_array($row['id'], $item))?$row:false;
}, $products);
Result dump:
Array
(
[0] => Array
(
[id] => 1
[name] => abc
)
[1] => Array
(
[id] => 2
[name] => xyz
)
)