【发布时间】:2015-01-28 00:35:33
【问题描述】:
我设计了房间预订系统,并以多维数组的形式存储数据。
这是数组(数据):
$recordBooking = array(
"111"=>array(
"date"=>array(
"29/10/2014"=>array(
array(
"from"=>1,
"to"=>3,
"user"=>"Amy",
"username"=>"CB34"
),
array(
"from"=>4,
"to"=>5,
"user"=>"Chars",
"username"=>"AA13"
)
),
"30/10/2014"=>array(
array(
"from"=>2,
"to"=>3,
"user"=>"Chars",
"username"=>"AA13"
),
array(
"from"=>3,
"to"=>6,
"user"=>"Gary",
"username"=>"SF11"
)
),
"02/11/2014"=>array(
array(
"from"=>1,
"to"=>3,
"user"=>"Billy",
"username"=>"V214"
)
),
.......
)
)
);
我还使用 foreach 循环来分隔数组值并存储这些数据。我使用数组 $BookArrRecord 来收集值并插入数据库。它导致 $BookArrRecord 只能存储每个日期的最后一个值的错误。谁能帮我找出问题以及如何改进?
foreach($recordBooking as $key => $value){
$rmNum[] = $key;
foreach($value as $k => $v){
foreach($v as $bookDate => $array){
$bookingDate[] = $bookDate;
foreach($array as $room => $info){
foreach($info as $period =>$fromTo){
if($period=="username"){
$userID[] = $fromTo;
}
if($period=="from"){
$from[] = $fromTo;
}
if($period=="to"){
$to[] = $fromTo;
}
}
}
}
}
}
for($rmCount=1;$rmCount<count($userID);$rmCount++){//get the $userID to set the rows of $rmNum
$rmNum[]+=$rmID[0];
}
$BookArrRecord = array();
foreach($rmNum as $key => $value){
$BookArrRecord[] = "('" . $userID[$key] . "', '" . $rmNum[$key] . "', '". $bookingDate[$key] . "', '" . $from[$key] . "', '" . $to[$key] . "')";
}
sql查询:
$bookingInformation = "INSERT INTO `bookRecord` (`userID`, `room_Number`, `date`, `frome`, `to`)
VALUES " . implode(',', $BookArrRecord);
查询的检查:
if(!mysql_query($bookingInformation, $dbConnection)){
die("Cannot access operation of Database(bookRecord): " . mysql_error()) . "<br>";
}else{
echo "Records added in table: BookingDate " . "<br>";
}
使用 var_dump 显示结果:
array(268) {
[0]=>
string(38) "('CB34', '111', '29/10/2014', '1', '3')"
[1]=>
string(38) "('AA13', '111', '30/10/2014', '4', '5')" //the date is wrong
[1]=>
string(38) "('AA13', '111', '02/11/2014', '2', '3')"
......
}
感谢您的帮助。
【问题讨论】:
-
请同时粘贴您的查询代码
-
如果你打印出 implode(',', $BookArrRecord); 你会得到什么?
-
谢谢 J A,我已经更新了结果,结果显示的日期格式错误。
标签: php mysql arrays for-loop multidimensional-array