doulian7252
2014-12-07 09:23
浏览 120
已采纳

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

Can't seem to get rtrim to work and I don't understand why:

$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 .= ";";

Why would this not get rid of the last comma?

it keeps printing out this:

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

图片转代码服务由CSDN问答提供 功能建议

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

  $ 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 两个',; 
   
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongyun65343 2014-12-07 09:28
    已采纳

    You have to assign the rtrim to $sql like that:

    $sql = trim($sql, ",");
    
    点赞 打赏 评论
  • douhuigang9550 2014-12-07 09:31

    Better way is to use implode(). Example:

    $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;
    }
    

    Output:

    INSERT INTO top SET one='inner one',two='inner two'
    
    点赞 打赏 评论
  • doujia7094 2014-12-07 09:31

    You forgot to overwrite $sql variable with rtrim result

     $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 .= ";";
    
    点赞 打赏 评论

相关推荐 更多相似问题