Farzan Najipour
Farzan Najipour

Reputation: 2503

php Laravel - find element in array

I want to use foreach to showing orderIds in my output.

Here is my code :

$orders = $results['result']['data'];
foreach ($orders as $key => $order)
{
     dd($order[$order]['orderId']);
}

here is $orders result :

  1 => array:3 [
    "orderId" => 4
    "orderTotalPrice" => 100
    }
    "resId" => 1
  ]
  2 => array:3 [
    "orderId" => 18
    "orderTotalPrice" => 100
    }
    "resId" => 1
  ]
  3 => array:3 [
    "orderId" => 34
    "orderTotalPrice" => 100
    }
    "resId" => 1
  ]
  4 => array:3 [
    "orderId" => 64
    "orderTotalPrice" => 100
    }
    "resId" => 1
  ]

Any suggestion?

Upvotes: 0

Views: 4478

Answers (3)

mirza
mirza

Reputation: 5793

"For showing orderId's in your output:"

$orders = $results['result']['data'];
foreach ($orders as $key => $order)
{
     echo $order['orderId'];
}

Upvotes: -1

Mike Barwick
Mike Barwick

Reputation: 5367

Maybe something like this?

$order_ids = [];

foreach ($orders as $order)
{
    array_push($order_ids, $order['orderId']);
}

return $order_ids;

As per @IsmailRBOUH's answer, use his solution if you're adding/pulling x-handful of data. If you're looping over a heavy amount of data, would be better (performance wise) to use array_push. But honestly, it's a fractional difference between them both. $array[] usually landing on top...

PHP's website:

Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

Upvotes: 3

Ismail RBOUH
Ismail RBOUH

Reputation: 10450

By using foreach you can do this:

$orderIDs = [];
foreach ($orders as $order){
     $orderIDs[] = $order['orderId'];
}

Or you can use the pluck method. It will retrieve all of the collection values for a given key:

collect($orders)->pluck('orderId')->all();

Upvotes: 4

Related Questions