0

I have a problem, namely, I do not know how to put new data into my array using the array_push() function in the foreach loop (to read database data). Code:

$result = array();
$i = 0;

#$rows - data from the database
foreach($res as $rows){
    $result[$i] = ['aa' => 'bb', 'cc' => 'dd', 'ee' => 'ff'];
    array_push($result[$i], ['gg' => 'hh', 'ii' => 'jj']);

    $i++;
}

#The expected result:
#Array('aa' => 'bb', 'cc' => 'dd', 'ee' => 'ff', 'gg' => 'hh', 'ii' => 'jj');

#Reality:
#Array(0 => ['gg' => 'hh', 'ii' => 'jj'], 'aa' => 'bb', 'cc' => 'dd', 'ee' => 'ff');

Thank you in advance for help.

Trawlr
  • 139
  • 1
  • 8
  • You need to explain what is in `$rows`. – ryantxr Aug 24 '17 at 22:18
  • what's the significance of `$rows` when you are not using it. and at the end each index of your final array is going to have exact same value – Anant Kumar Singh Aug 24 '17 at 22:26
  • Possible duplicate of [PHP append one array to another (not array\_push or +)](https://stackoverflow.com/questions/4268871/php-append-one-array-to-another-not-array-push-or) – mickmackusa Aug 25 '17 at 01:10

1 Answers1

0

You have to do it like below:-

<?php

$result[] = ['aa' => 'bb', 'cc' => 'dd', 'ee' => 'ff'];
$result = array_merge($result[0], ['gg' => 'hh', 'ii' => 'jj']);

print_r($result);

https://eval.in/850034

Anant Kumar Singh
  • 68,309
  • 10
  • 50
  • 94