phparraysloopsmultidimensional-arraydeclaration

How to build a 2d array with static and dynamic data while looping?


I'm using a foreach loop to create an array from database values like so:

foreach ($query->result_array() as $row) {
   array(
      'user_id'  => $user_id,
      'post_id'  => $row['id'],
      'time'     => '0',
      'platform' => $platform
   );
}

Let's say I pull 2 rows, I need to make this foreach create a multidimensional array in the following format:

$data = array(
    array(
       'user_id'  => '12', 
       'post_id'  => '37822', 
       'time'     => '0',
       'platform' => 'email'
    ),
    array(
       'user_id'  => '12', 
       'post_id'  => '48319', 
       'time'     => '0',
       'platform' => 'email'
    ),
);

Solution

  • You can first declare an empty array :

    $results = array();
    

    then, each time you have a new row, add it to that array :

    $results[] = $row;
    

    Or, anyway, to add anything into that array :

    $results[] = array( something here );
    


    In your specific case, you'd probably use something like this :

    $results = array();
    foreach ($query->result_array() as $row) {
        $results[] = array(
                        'user_id' => $user_id, 
                        'post_id' => $row['id'], 
                        'time' => '0', 
                        'platform' => $platform
                    );
    }
    


    As a reference, the corresponding section of the PHP manual : Creating/modifying with square bracket syntax.