0

I have a prepared statement to draw information from a database. There are 3 fields of information drawn from the database and an unknown number of rows.

I have a 'while' loop to define what should happen to the information gained from each row. I would like to create an array for the 3 fields of information to sit in for each row, then an array for all of these arrays to sit in (i.e. a 2D array).

Here's my code so far:

$bArray = [];
$bList = $mysqli->prepare('SELECT blog_title,blog_date,blog_id FROM cms_blog');
$bList->execute();
$bList->bind_result($bListTitle,$bListDate,$bListId);
while ($bList->fetch()) {
  $bArray['bTitle']=$bListTitle;
  $bArray['bDate']=$bListDate;
  $bArray['bId']=$bListId;
}

I would like the array to look something like this once complete:

Array (
  Array (
    [blogTitle] => First title
    [blogDate] => First date
    [blogId] => First ID
  )
  Array (
    [blogTitle] => Second title
    [blogDate] => Second date
    [blogId] => Second ID
  )
) 

Is there a way to write this? I only need key pairs for the inner arrays.

2 Answers 2

1

Try this code:

$bArray = array();
$bList = $mysqli->prepare('SELECT blog_title,blog_date,blog_id FROM cms_blog');
$bList->execute();
$bList->bind_result($bListTitle,$bListDate,$bListId);
while ($bList->fetch()) {
  $iArray=array();  // Inner array
  $iArray['bTitle']=$bListTitle;
  $iArray['bDate']=$bListDate;
  $iArray['bId']=$bListId;
  $bArray[] = $iArray;   // Insert the inner array into $bArray
}
2
  • Works perfectly thanks! Just out of curiousity, is it better to declare the array variables like $bArray = []; or $bArray = array();? Commented Feb 6, 2014 at 22:50
  • sorry, I don't know what's better. I use array() and it works ;) Commented Feb 6, 2014 at 23:04
0

Maybe you need to use this:

for ($row = 0; $row < 3; $row++)
{
    for ($col = 0; $col < 3; $col++)
    {
        $var[$row][$col]="col: ".$col." Row: ".$row;
    }
}

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.