Search code examples
phparraysmultidimensional-arrayfilterarray-filter

Pull an element of an array according to one of the matches


I have two arrays:

$productIds = [
    ['product_id' => 12, 'price' => 1234],
    ['product_id' => 13, 'price' => 1235],
    ['product_id' => 14, 'price' => 1236]
];

$ids = [12, 14];

Then I iterate array $ids and must extract the array I need from the array $productIds by product ID:

$data = [];
foreach ($ids as $id) {
    $data[] = ... // get data by $id (equal 'product_id') from $productIds
}

At the output, I want to get such an array:

$data = [
    ['product_id' => 12, 'price' => 1234],
    ['product_id' => 14, 'price' => 1236]
];

But the solution must be without a nested cycle (foreach).


Solution

  • You can do it like this,

            $productIds = array_column($productIds,null,"product_id");
            $result = [];
            foreach($ids as $id){
                $result[] = $productIds[$id];
            }