PHP TIPS:遍历数组且最后一个元素执行其他方法

发布于 2020-12-16  994 次阅读


php遍历数组且最后一个元素执行其他方法

需求: 封装一个方法,通过给予array ,方法内遍历array,将keyvalue进行拼接,最后实现完整的sql查询功能。

    /**
     * 根据条件数组构建sql语句
     * array(
     *  'log_id'=>'',
     *  'log_level'=>'',
     *  'log_action'=>'',
     * `'log_user'=>'',
     *  'log_message'=>'',
     * );
     *
     * @param string $conditions_array
     * @return array 
     * @author siroi
     * @time 2020年12月16日17:00:44
     */
public function selectSql($conditions_array){
    foreach ($conditions_array as $key => $value) {
        //如果值不等于最后一个 do something
              if($value != end($conditions_array)){
                  //something
                  $where_sql .= " ".$key." = '".$value."' and";
              }else{
                  $where_sql .= " ".$key." = '".$value."'";
              }
            }  
            $sql = 'select * from '.$this->dbname.' where '.$where_sql;
    reture $sql;
}

With great power there must come great responsibility.