循环对象的有效方法

时间:2014-06-30 06:37:49

标签: php object

我的页面中有一个部分可以添加,编辑或删除学校详细信息,并且在用户点击进入之前不应该将条目保存到数据库中,因此我首先将所有数据保存在对象中。我的对象看起来像这样:

schooldetails : {
  "1": {
    "school_ctr":"schoolctr_1",
    "school":"Fiat Lux Academe",
    "course":"",
    "qualification":"High School",
    "date_grad":"06/04/2008",
    "notes":"*graduated with honors",
    "deleted":0
  },
  "2": {
    "school_ctr":"schoolctr_2",
    "school":"College of St. Benilde",
    "course":"Computer Science",
    "qualification":"Bachelor / College",
    "date_grad":"06/05/2012",
    "notes":"",
    "deleted":0
  },
  "3":{
    "school_ctr":"schoolctr_3",
    "school":"Siliman University",
    "course":"Information Technology",
    "qualification":"Post Graduate / Master",
    "date_grad":"06/06/2014",
    "notes":"",
    "deleted":0
  }
}

我通过ajax传递了它,我能够通过以下代码保存信息:

if(!empty($school_details_new)){
  foreach($school_details_new as $key => $value) {
    foreach($value as $school_data => $data_values) {
      if($school_data == "school")
        $s_name = mysql_real_escape_string($data_values);
      if($school_data == "course")
        $s_degree = mysql_real_escape_string($data_values);
      if($school_data == "qualification")
        $s_type = mysql_real_escape_string($data_values);
      if($school_data == "date_grad")
        $s_enddate = mysql_real_escape_string($data_values);
      if($school_data == "notes")
        $s_notes = mysql_real_escape_string($data_values);                      
    }
  $sql = "INSERT INTO `SchoolDetails` (`personID`, `School`, `Type`, `End_Date`, `Degree`, `Notes`) VALUES ($id, '$s_name', '$s_type', '$s_enddate', '$s_degree', '$s_notes');";
  $res_sql = mysql_query ($sql);
  }
}

这实际上对我很好,我没有任何错误或任何其他但我相信有一个更有效的方法来做到这一点,而没有很多“if”语句。思考?提前谢谢。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

if (!empty($school_details_new)) {
foreach ($school_details_new as $key => $value) {

    $s_name = mysql_real_escape_string($value['school']);
    $s_degree = mysql_real_escape_string($value['course']);
    $s_type = mysql_real_escape_string($value['qualification']);
    $s_enddate = mysql_real_escape_string($value['date_grad']);
    $s_notes = mysql_real_escape_string($value['notes']);

    $sql = "INSERT INTO `SchoolDetails` (`personID`, `School`, `Type`, `End_Date`,  `Degree`, `Notes`) VALUES ($id, '$s_name', '$s_type', '$s_enddate', '$s_degree', '$s_notes');";
    $res_sql = mysql_query($sql);
}

}