1

I'm struggling with array_merge to make an array of items. The code which I have:

$items = [];
foreach ($products as $product) {
    Log::info($product->orderproduct->idorder_product);

    $items = array_merge($items, [
       'id'          => $product->orderproduct->idorder_product
    ]);
}
Log::info(print_r($items, true));

The output is:

6
7
['id' => 7]

How can I create an array with both id's?

5
  • how many items you have in $products?? Commented Apr 3, 2019 at 7:12
  • $items[$id] = $product->orderproduct->idorder_product; should be sufficient if all your doing is populating an array keyed by ID? Commented Apr 3, 2019 at 7:12
  • 1
    You can only have one key called 'id'. In other words, each key must be unique. Commented Apr 3, 2019 at 7:14
  • According to the manual: If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. As an alternative to the answer below, using array_merge(), you would would have to merge [[ ... ]] instead of [ ... ]. Commented Apr 3, 2019 at 7:15
  • i think your problem is that you're using the index "id" and overwriting it each time in that loop. like people already suggested, use $items[] = ['id' => $product->orderproduct->idorder_product]; to create autoincrement numeric index for each array you're adding into $items. Commented Apr 3, 2019 at 7:16

2 Answers 2

4

Not sure what result you expect, so there are 2 options:

foreach ($products as $product) {
    Log::info($product->orderproduct->idorder_product);

    // First
    $items[] = $product->orderproduct->idorder_product;
    // Second
    $items[] = ['id' => $product->orderproduct->idorder_product];
}
Sign up to request clarification or add additional context in comments.

Comments

0

Array merge is just another array which add into the bottom of the array. I think you are misleading us on the result you want to get.

$items = array(); / $items = [];

you can push the data into array easily by this code

$items[] = array(
 'id' => $product->orderproduct->idorder_product,
)

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.