【问题标题】:PHP - How to loop 2 set of arrays and mix them together?PHP - 如何循环 2 组数组并将它们混合在一起?
【发布时间】:2012-11-26 14:14:19
【问题描述】:

我在循环数组并将它们混合为一组新数据时遇到问题。第一组数组是房间 ID。另一组是日期范围。我想每天在数组中包含房间 ID 的范围内循环。

这是我的资源:

$_rid=array("5","6");
$date_range=getDays('2012-11-30','2012-12-05');
$_sid=md5(time());

获取两天之间的日期函数:

function getDays($strDateFrom,$strDateTo) {
  // takes two dates formatted as YYYY-MM-DD and creates an
  // inclusive array of the dates between the from and to dates.

  // could test validity of dates here but I am already doing
  // that in the main script

  $aryRange=array();

  $iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2),     substr($strDateFrom,8,2),substr($strDateFrom,0,4));
  $iDateTo=mktime(1,0,0,substr($strDateTo,5,2),     substr($strDateTo,8,2),substr($strDateTo,0,4));

  if ($iDateTo>=$iDateFrom) {
    array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry

    while ($iDateFrom<$iDateTo) {
      $iDateFrom+=86400; // add 24 hours
      array_push($aryRange,date('Y-m-d',$iDateFrom));
    }
  }
  return $aryRange;
}

所以我写了:

foreach($_POST[vid] as $_vidz){//5-6
    foreach($date_range as $val0){  
    //get cost from villas_rate each date
    $sql_rCost="select vr_cost from villas_rate where vr_id='$_vidz'";
    //echo $sql_rCost."<hr />";
    $result_rCost=mysql_db_query($dbname,$sql_rCost);
    while($rec_rCost=mysql_fetch_array($result_rCost)){
        $_rCostDBcost=explode("-",str_replace(",","",$rec_rCost['vr_cost']));   
            $_rate=$_rCostDBcost[$_rtype-1];//rate starts with 0
            $_date=$val0;
            $sql_cBk="insert into booking_customer values('','$_sid','$_vidz','$_rate','$_agc','$_date')";
            echo $sql_cBk."<br />";             
        }
    }
}

结果 结果应该是好的。但它只循环数组 $_rid=5 中的一个值。

insert into booking_customer values('','e1eb3f2e2c0fe99780c0354fa699a827','5','2012-11-30')
insert into booking_customer values('','e1eb3f2e2c0fe99780c0354fa699a827','5','2012-12-01')
insert into booking_customer values('','e1eb3f2e2c0fe99780c0354fa699a827','5','2012-12-02')
insert into booking_customer values('','e1eb3f2e2c0fe99780c0354fa699a827','5','2012-12-03')
insert into booking_customer values('','e1eb3f2e2c0fe99780c0354fa699a827','5','2012-12-04')
insert into booking_customer values('','e1eb3f2e2c0fe99780c0354fa699a827','5','2012-12-05')

【问题讨论】:

  • 很好sql injection hole。希望你喜欢你的服务器 pwn3d。您可能想阅读DateTime 对象,这将为您节省很多您正在做的无意义的日期/字符串操作。
  • @MarcB,如果您发现任何问题或有改进的机会。请不要犹豫,向我展示几行示例代码。谢谢

标签: mysql arrays loops foreach


【解决方案1】:

可能您在 HTML 表单中使用了诸如 &lt;input name="vid" .. &lt;input name="vid" .. 之类的输入名称,在这种情况下您遇到了麻烦:

foreach($_POST[vid] as $_vidz)

您应该使用带有[] 的名称,例如&lt;input name="vid[]" .. &lt;input name="vid[]" ..

或者在villas_rate 中不存在vr_id = 6 的记录

【讨论】:

  • 伊万,谢谢你的建议。我从以前的表单发送 vid 值是错误的。
猜你喜欢
  • 2017-03-22
  • 1970-01-01
  • 1970-01-01
  • 2015-04-06
  • 2021-01-28
  • 2020-12-16
  • 2014-05-29
  • 2013-11-20
  • 2015-10-16
相关资源
最近更新 更多