动态创建数组

时间:2012-02-22 06:14:18

标签: php sql-server arrays multidimensional-array

我正在尝试使用php

动态创建数组
 $data =    array(
  array("date" => "1/2/2012", "sentstatus" => "0", "mobile" => "14578998"),
      array("date" => "21/2/2012", "sentstatus" => "1", "mobile" => "14668998"),
      array("date" => "1/5/2012", "sentstatus" => "1", "mobile" => "14598998"),
      array("date" => "1/6/2012", "sentstatus" => "0", "mobile" => "14578748"),
);

下面是我的PHP代码,它将sql server数据插入到数组中,但问题是数组是由数据库表的最后结果集行组成的。我没有想到将所有数据库表行插入到数组中,如上所示:

 $sql = "SELECT [start_date_time],[sent_status],[mobile_number] ,[play_file] 
         FROM [slice].[dbo].[tbl_message_detail] ";
 $res = odbc_exec($con,$sql) or die(odbc_error());
 $rows = odbc_num_rows($res);

 while($row = odbc_fetch_array($res))
  {     
 $data =  array(
         array("Date_Time" => $row['start_date_time'], "Send_Status" => $row['sent_status'], "Mobile_Number" => $row['mobile_number'], "play_file" => $row['play_file'])
    );
   }

3 个答案:

答案 0 :(得分:1)

您只获得最后一行,因为您在每次迭代时都在创建一个新数组。在$data循环之外声明while

答案 1 :(得分:1)

试试这段代码:

while($row = odbc_fetch_array($res))
{     
  $data[] =  array("Date_Time" => $row['start_date_time'], 
                   "Send_Status" => $row['sent_status'], 
                   "Mobile_Number" => $row['mobile_number'], 
                   "play_file" => $row['play_file']);
}

答案 2 :(得分:1)

你在每一轮循环中覆盖了$ data变量。这样:

$data = array();
while($row = odbc_fetch_array($res))
{     
 $data[] = array("Date_Time" => $row['start_date_time'], 
                 "Send_Status" => $row['sent_status'], 
                 "Mobile_Number" => $row['mobile_number'], 
                 "play_file" => $row['play_file']
           );
}

应该按你的需要工作