从字符串rtrim中删除最后一个逗号

时间:2014-12-07 09:23:05

标签: php trim

似乎无法让rtrim工作,我不明白为什么:

$array = array("top" => array("one" => "inner one", "two" => "inner two"));

foreach (array_keys($array) as $key) {
  $form[$key] = array();
  $sql = "INSERT INTO $key SET ";
  foreach (array_keys($array[$key]) as $field) {
    array_push($form[$key], $field);
    $sql .= $field." = '".$array[$key][$field]."',";
  }
}
  rtrim($sql,',');
  $sql .= ";";

为什么这不会删除最后一个逗号?

它不断打印出来:

INSERT INTO top SET one = 'inner one',two = 'inner two',;

3 个答案:

答案 0 :(得分:3)

您必须将rtrim分配给$sql

$sql = trim($sql, ",");

答案 1 :(得分:1)

更好的方法是使用implode()。例如:

$array = array("top" => array("one" => "inner one", "two" => "inner two"));
foreach($array as $key=>$val){
    $form = array();
    $sql = "INSERT INTO $key SET ";
    foreach ($val as $k=>$field) {
        array_push($form, $k."='".$field."'");
    }
    $sql .= implode(",",$form);
    //echo $sql;
}

<强>输出:

INSERT INTO top SET one='inner one',two='inner two'

答案 2 :(得分:0)

您忘记使用rtrim结果覆盖$ sql变量

 $array = array("top" => array("one" => "inner one", "two" => "inner two"));

 foreach (array_keys($array) as $key) {
   $form[$key] = array();
   $sql = "INSERT INTO $key SET ";
   foreach (array_keys($array[$key]) as $field) {
     array_push($form[$key], $field);
     $sql .= $field." = '".$array[$key][$field]."',";
   }
 }
 $sql = rtrim($sql,',');
 $sql .= ";";