在while循环中创建2D PHP数组

时间:2021-07-27 01:30:34

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.

我有一个准备好的声明来从数据库中提取信息。从数据库中提取了3个信息字段,并且行数未知。

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).

我有一个'while'循环来定义从每一行获得的信息应该发生什么。我想创建一个数组,用于3个字段的信息,以便为每一行坐下,然后为所有这些数组创建一个数组(即2D数组)。

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 个解决方案

#1


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


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;
    }
}

#1


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


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;
    }
}