3

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'
    ),
);
1
  • $data[]=array(what you already have); Commented Jul 23, 2011 at 6:20

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.