-1

I may seem having difficulty in understanding on how array works. So result, I can't work on the issue.

foreach($results as $key => $value){
    $product_key = array(
      'key' => $key
    );
    array_push($results, $product_key);
}

var_dump($results); exit;

Expected Output

array(2) {
  [0]=>
  object(stdClass)#21 (4) {
    ["items_id"]=>
    string(1) "1"
    ["item_name"]=>
    string(6) "laptop"
    ["price"]=>
    string(5) "20000"
    ["quantity"]=>
    string(2) "10"
    ["key"]=>
    int(0)
  }
  [1]=>
  object(stdClass)#22 (4) {
    ["items_id"]=>
    string(1) "2"
    ["item_name"]=>
    string(10) "smartphone"
    ["price"]=>
    string(5) "10000"
    ["quantity"]=>
    string(3) "200"
    ["key"]=>
    int(1)
  }

Unexpected Output

array(4) {
  [0]=>
  object(stdClass)#21 (4) {
    ["items_id"]=>
    string(1) "1"
    ["item_name"]=>
    string(6) "laptop"
    ["price"]=>
    string(5) "20000"
    ["quantity"]=>
    string(2) "10"
  }
  [1]=>
  object(stdClass)#22 (4) {
    ["items_id"]=>
    string(1) "2"
    ["item_name"]=>
    string(10) "smartphone"
    ["price"]=>
    string(5) "10000"
    ["quantity"]=>
    string(3) "200"
  }
  [2]=>
  array(1) {
    ["key"]=>
    int(0)
  }
  [3]=>
  array(1) {
    ["key"]=>
    int(1)
  }
}
Emjey23
  • 339
  • 1
  • 4
  • 16

1 Answers1

2

You push new value (which is array) to the end of existsing array, what do you expect then?

If you want to modify current interated array value use this approach:

foreach($results as $key => $value) {
    // use `->` as `$value` is object
    $value->key = $key;
}

var_dump($results); exit;
u_mulder
  • 54,101
  • 5
  • 48
  • 64