1

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).

LF00
  • 27,015
  • 29
  • 156
  • 295
Brandsley
  • 97
  • 1
  • 7

1 Answers1

2

You can do it like this,

        $productIds = array_column($productIds,null,"product_id");
        $result = [];
        foreach($ids as $id){
            $result[] = $productIds[$id];
        }
LF00
  • 27,015
  • 29
  • 156
  • 295