php学习之路

1.php拼接字符串+查询

$floor_id = M('house_floor_input')->where($map1)->field('id')->select();
$floor_id_str = '';
foreach ($floor_id as $k => $v) {

       //去,
       if($k==count($floor_id)-1){
          $floor_id_str .= $v['id'];
       }

        //拼接条件带,

       else{
          $floor_id_str .= $v['id'].',';
      }
}
$map['f_id'] = array('in',$floor_id_str);
$list = M('house_input')->where($map)->order('id desc')->select();

3.php拆分

 

//查看该房型详细内容
$info = M('house_floor_input')->where(array('token' =>get_token() ,'f_name'=>I('id') ))->find();
//特色字段的拆分
$feature = explode(',', $info['f_features']);

$this->assign('feature',$feature);

 

 

2.php模糊查询

$map1['f_name'] = array('like','%'.I('lpname').'%');  

3.getField获取单挑

$floorinput = M('house_floor_input')->where($map1)->getField('f_name'); 

4.field获取集合

$floor_id = M('house_floor_input')->where($map1)->field('id')->select(); 

5.php前端页面运用三元表达式

<a {$type == '1' ? 'class="nav_item active"' : 'class="nav_item flex-box-1"'} href="{:U('index',array('type'=>1))}">最热</a>

<li class="miaosha" <if condition="$fy['h_tuijian'] neq 1">style="display:none"</if> ><div>马上秒杀</div></li>

6.去重查询

$project = M('dreammore_support_person')->distinct(true)->where(array('p_token'=>get_token(),'p_openid'=>get_openid()))->getField('p_project_id',true);

7.php ajax提交

var url="{:U('loginAuth','','')}";
$.ajax({
url:url,
data:"account=" + account + "&password=" + password,
type:"post",
dataType:"json",
error:function(){errorPrompt('账户或密码错误');},
success:function(data){
if (data == "success") {
window.location.href = $("#url").val();
}
}
});

8.thinkphp中的比较符号

Thinkphp中eq,neq,gt,lt等表达式缩写

eq 等于
neq 不等于
gt 大于
egt 大于等于
lt 小于
elt 小于等于
like LIKE
between BETWEEN
notnull IS NUT NULL
null IS NULL

/*thinkphp在另一个问题中的回帖*/

egf 是表示数据库的字段比较,而非字符串比较
例如:
$map['name']  = array('eq','label'); 和
$map['name'] = array('eqf','label');
分别代表 name = 'label' 和 name = label 
同样的道理,gt lt 等其他表达式也可以在后面添加f来表示同样的功能~
 
9.php 插入数据库当前时间非时间戳格式
$data['ctime'] = Date('Y-m-d H:i:s');
时间戳格式:time()
时间戳转格式:{$fy.h_endtime|date="Y-m-d",###}
 
10.二位数组插入二位数组

$myCouponOrder = M('house_coupon_order')->where(array('token'=>get_token(),'openid'=>$openid))->select();
foreach ($myCouponOrder as $c_id => &$vo1) {
   $id = $vo1['c_id'];
   $myCouponDetail = M('house_coupon')->where(array('id'=>$id))->find();
   $myCouponDetails[$id]['c_detail'] = $myCouponDetail;
}

$this->assign('myCouponDetails',$myCouponDetails);

输出前台

<volist name="myCouponDetails" id="vo1">
<li class="ui-border-t">
<div class="ui-list-img">
<span style="background-image:url({$vo1['c_detail']['c_picture']|get_cover_url}); background-size:100%;"></span>
</div>
<div class="ui-list-info">
<h4 class="ui-nowrap lp-title">{$vo1['c_detail']['c_title']}</h4>
<p class="ui-nowrap">总量:{$vo1['c_detail']['c_total']}</p>
<p class="ui-nowrap">已秒杀:{$vo1['c_detail']['c_skilledCount']}</p>

<h5 class="ui-nowrap n-price">¥{$vo1['c_detail']['c_skillprice']}元</h5>
<p class="ui-nowrap fav-box"><i class="ui-icon-emo"></i>感兴趣:{$vo1['c_detail']['c_hot']}</p>
<button class="wantosee" name="test" type="button" value="val">
<a href="{:U('coupondetail',array('c_id'=>$vo1['c_detail']['id']))}">查看详情</a>
</button>
</div>
</li>
</volist>

11.php导出excel

//导出活动支付
public function exportExecel(){
$map['c_title'] = I('c_title');
$map['token'] = get_token();
$row = M('house_coupon_order')->where($map)->select();

$filename=$map['c_title'].date('Y-m-d').".xls";//先定义一个excel文件
header("Content-Type: application/vnd.ms-execl");
header("Content-Type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");

echo codeutf8("订单号")."\t";
echo codeutf8("商品名")."\t";
echo codeutf8("支付金额")."\t";
echo codeutf8("客户名")."\t";
echo codeutf8("联系方式")."\t";
echo codeutf8("下单时间")."\n";

foreach ($row as $key => $vo) {
echo codeutf8($vo['orderid'])."\t";
echo codeutf8($vo['c_title'])."\t";
echo codeutf8($vo['price'])."\t";
echo codeutf8($vo['name'])."\t";
echo codeutf8($vo['phone'])."\t";
echo codeutf8($vo['ctime'])."\n";
}
}

 

//导出excel编码标题(防止乱码)

function codeutf8($str){
return iconv("utf-8","gb2312",$str);
}

 

12.  implode和explode

$imags = array([0]=123,[1]=345,[2]=121)   

$imags  = implode(',', $imgs);

$imags  = explode(',',$imags ,-1);

var_dump($imags);

array([0]=123,[1]=345,[2]=121) 

 

13.json

// public function vote_index_json(){
// $database = C('DB_NAME');
// $table = C('DB_PREFIX').mengvote_baoming;
// $host = C('DB_HOST');
// $user = C('DB_USER');
// $pwd = C('DB_PWD');
// $link = mysql_connect("".$host."","".$user."","".$pwd."");
// $sql = "use ".$database."";
// mysql_query($sql,$link);
// $sql = "set names utf8";
// mysql_query($sql,$link);
// $num = $_POST['num'] *10;
// if($_POST['num'] != 0) $num +1;
// $sql = "select id,m_no,m_name from ".$table." limit ".$num.",10";
// $result = mysql_query($sql,$link);
// $temp_arr = array();
// while($row = mysql_fetch_assoc($result)){
// $temp_arr[] = $row;
// }
// $json_arr = array();
// foreach($temp_arr as $k=>$v){
// $json_arr[] = (object)$v;
// }
// //print_r($json_arr);die;
// echo json_encode( $json_arr );
// }

 

13.html嵌套php

<?php
$img = $info['m_img'];
$array=explode(',',$img);
$imgs = explode(',',$img,-1);
//数组长度
$len = count($array);
//$imgs = explode(',',$img,-1);
for($i=0; $i < $len; $i++) { ?>
<img src="<?php echo get_cover_url($imgs[$i]); ?>" alt="">
<?php
}
?>

 

14 json html();

var that = $('#mainPage .user-info ul li .location1'),_html='';
var url="{:U('addressManagement','','')}";
$.ajax({
url:url,
data:"username=" + username + "&userphone=" + userphone+ "&province=" + province+ "&city=" + city+ "&dist=" + dist+ "&address=" + address+ "&community=" + community+ "&area=" + area,
type:"post",
dataType:"json",
error:function(){errorPrompt('账户或密码错误');},
success:function(data){
alert(data.length);

_html ='<span class="title">'+data[0]['user_name']+'</span>'+
'<span class="content">'+
'<span class="btn-link">'+data[0]['user_phone']+'</span><br>'+
'<span class="address">'+data[0]['user_address']+'</span>'+
'</span>'+
'<i class="icon arrow"></i>';
that.html(_html);
$("#mainPage").attr('style','position:absolute;left:0%;');
$("#addressPage").attr('style','position:absolute;left:-100%;');
$("#addressListPage").attr('style','position:absolute;left:-100%;');
$("#addressEditPage").attr('style','position:relative;left:-100%;');
}
});
});

each

$(".location1").click(function(){
var that = $('#addressPage .order-address ul'),_html='';
var url="{:U('addressNew','','')}";
$.ajax({
url:url,
type:"post",
dataType:"json",
success:function(data){
$.each(data, function(idx, obj) {
_html += '<li><a href="javascript:void(0);">'+
'<label data-id="178717" class="active">'+
'<p class="c333">'+
'<span class="name">'+obj.user_name+'</span>'+
'<span class="tel">'+obj.user_phone+'</span>'+
'</p>'+
'<p class="c999 address">'+obj.user_address+'</p>'+
'</label></a></li>';
});
that.html(_html);
}
});

$("#mainPage").attr('style','position:absolute;left:-100%;');
$("#addressPage").attr('style','position:absolute;left:0%;');
$("#addressListPage").attr('style','position:absolute;left:-100%;');
$("#addressEditPage").attr('style','position:relative;left:-100%;');
});

15.ajax 请求到数据库加载到html,用jquery获取加载后html中的元素的方法

$(document).ready(function(e) {
$("#addressPage .order-address ul").delegate("li","click",function(){
var username = $(this).children('a').children('label').children('p:first').children('span:first').text();
var userphone = $(this).children('a').children('label').children('p:first').children('span:last').text();
var useraddress = $(this).children('a').children('label').children('p:last').text();

$('#mainPage .user-info .location1').children('span:first').text(username);
$('#mainPage .user-info .location1').children('span:last').children('span:first').text(userphone);
$('#mainPage .user-info .location1').children('span:last').children('span:last').text(useraddress);

$("#mainPage").attr('style','position:absolute;left:0%;');
$("#addressPage").attr('style','position:absolute;left:-100%;');
$("#addressListPage").attr('style','position:absolute;left:-100%;');
$("#addressEditPage").attr('style','position:relative;left:-100%;');
});

$("#addressListPage ul.b").delegate('li','click',function(){
var name = $(this).children('a').children('label').children('p:first').children('span:first').text();
var tel = $(this).children('a').children('label').children('p:first').children('span:last').text();
var address = $(this).children('a').children('label').children('p:last').text();
$("#mainPage").attr('style','position:absolute;left:-100%;');
$("#addressPage").attr('style','position:absolute;left:-100%;');
$("#addressListPage").attr('style','position:absolute;left:-100%;');
$("#addressEditPage").attr('style','position:relative;left:0%;');
});
});

16.mb_substr()

一、中文截取:mb_substr()

    mb_substr( $str, $start, $length, $encoding )

    $str,需要截断的字符串

    $start,截断开始处,起始处为0

    $length,要截取的字数

    $encoding,网页编码,如utf-8,GB2312,GBK

    实例:

    复制代码代码如下:

   

    $str='脚本之家:http://www.jb51.net';

    echo mb_substr($str,0,4,'utf-8');//截取头5个字,假定此代码所在php文件的编码为utf-8

    ?>

    结果显示:脚本之家

    二、获取中文长度:mb_strlen()

    mb_strlen( $str, $encoding )

    $str,要计算长度的字符串

    $encoding,网页编码,如utf-8,GB2312,GBK

    实例:

    复制代码代码如下:

   

    $str='脚本之家:http://www.jb51.net';

    echo mb_strlen($str,'utf-8');//假定此代码所在php文件的编码为utf-8

    ?>

    结果显示:24

 

17.计算两个时间戳之间的差

本函数实现两个unix时间戳的差,并返回两个时间戳相差的天、小时、分、秒,精确到秒,两个参数都是时间戳,虽然代码很简单,但是很实用。
function timediff($begin_time,$end_time) 

      if($begin_time < $end_time){ 
         $starttime = $begin_time; 
         $endtime = $end_time; 
      } 
      else{ 
         $starttime = $end_time; 
         $endtime = $begin_time; 
      } 
      $timediff = $endtime-$starttime; 
      $days = intval($timediff/86400); 
      $remain = $timediff%86400; 
      $hours = intval($remain/3600); 
      $remain = $remain%3600; 
      $mins = intval($remain/60); 
      $secs = $remain%60; 
      $res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs); 
      return $res; 
}

 

18.判断是否微信内置浏览器

/**
* 判断是否微信内置浏览器
*/
function isWeixin() {
var ua = navigator.userAgent.toLowerCase();
if (ua.match(/microMessenger/i) == "micromessenger") {
return true;
} else {
return false;
}
}

 

19. sql 拼接一列值,例如凭借id的所有值为1,2,3

$category_id = $this->query_all("SELECT id FROM " .get_table('category')." WHERE parent_id = ".$parent);
foreach ($category_id as $k => $v) {
$category_ids[] = $v['id'];
}
$where = implode(',', $category_ids);

var_dump($where);die;

20.{template 'header'} <title>专业装逼30年</title> 

引入header时title中文乱码

原因:<header></header>内有没有闭合的标签

 

21.给一组$orders 加上一列值good_num的构造方法:

$orders = pdo_fetchall("SELECT * FROM ".tablename('hao_water_order')." WHERE uniacid = '{$uniacid}' ORDER BY order_time DESC LIMIT ".($pindex - 1) * $psize.','.$psize);
        
  foreach ($orders as $k => &$v) {
	        $goodId = explode(',',$v['goodsId']); 
	        $num = explode(',',$v['order_count']); 
	        $len = count($v['goodsId']);
	        for($i=0;$i<$len;$i++){
	           $good = pdo_fetch("SELECT * FROM ".tablename('hao_water_goods')." WHERE id = :id LIMIT 1",array(':id' => $goodId[$i]));
	           $good_nums[] = $good['goods_title'].'*'.$num[$i];
	        }
	        $v['good_num'] = implode(',',$good_nums);
 }

22 占位符替换

<?php
    $str = str_replace("#员工#", "豪哥", "i love #员工#, iwind #员工号#");
    $str = str_replace("#员工号#", "1101", $str);
    var_dump($str);
//输出
    'i love 豪哥, iwind 1101' (length=25)
?>

 

posted @ 2016-05-09 10:42  kobe工作室  阅读(344)  评论(0编辑  收藏  举报