0

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?

2
  • 1
    From where do those } come from? Commented Jul 9, 2016 at 5:40
  • @Rizier123 I edited my question. Commented Jul 9, 2016 at 5:48

3 Answers 3

4

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();
Sign up to request clarification or add additional context in comments.

3 Comments

I don't think you need to declare the $orderIDs = []; prior to the foreach in this case...right?
You're def right ;) I don't know, maybe it's a habit from other languages !
Which makes it a tad cleaner solution (less code). Problem is, if you're looping through a lot of data, makes more sense to use array_push over your method. Better performance. If you needed to append a single item or two, this would make more sense. Either option should help the poster - +1 for the collect() method! :)
3

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.

Comments

-1

"For showing orderId's in your output:"

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.