PHP 实现无限极分类生成分类树的方法

<?php

$data = array (
  array (
    'id' => 4,
    'category_name' => '要闻',
    'pid' => 3,
    'created_at' => '2018-06-21 17:33:55',
    'updated_at' => '2018-06-21 17:33:55',
  ),
  array (
    'id' => 3,
    'category_name' => '新闻',
    'pid' => 0,
    'created_at' => '2018-06-21 17:33:45',
    'updated_at' => '2018-06-21 17:33:45',
  ),
  array (
    'id' => 5,
    'category_name' => '企业服务',
    'pid' => 3,
    'created_at' => '2018-06-21 17:34:12',
    'updated_at' => '2018-06-21 17:34:12',
  ),
  array (
    'id' => 6,
    'category_name' => '大新闻',
    'pid' => 0,
    'created_at' => '2018-06-26 14:41:28',
    'updated_at' => '2018-06-26 14:41:28',
  ),
  array (
    'id' => 7,
    'category_name' => '优惠',
    'pid' => 6,
    'created_at' => '2018-06-26 14:41:45',
    'updated_at' => '2018-06-26 14:41:45',
  ),
);
echo "<pre>";
//var_export($data);



function getTree($list,$pid=0,$level=0) {
  static $tree = array();
  foreach($list as $row) {
    if($row['parentID']==$pid) {
      $row['level'] = $level;
      $tree[] = $row;
      getTree($list, $row['id'], $level + 1);
    }
  }
  return $tree;
}

function makeTree($arr){
  $refer = array();
  $tree = array();
  foreach($arr as $k => $v){
    $refer[$v['id']] = & $arr[$k]; //创建主键的数组引用
  }
  foreach($arr as $k => $v){
    $pid = $v['pid'];  //获取当前分类的父级id
    if($pid == 0){
      $tree[] = & $arr[$k];  //顶级栏目
    }else{
      if(isset($refer[$pid])){
        $refer[$pid]['subcat'][] = & $arr[$k]; //如果存在父级栏目,则添加进父级栏目的子栏目数组中
      }
    }
  }
  return $tree;
}


$a = makeTree($data);
print_r($a);

$b = getTree($data);
print_r($b);

输出:

Array
(
    [0] => Array
        (
            [id] => 3
            [category_name] => 新闻
            [pid] => 0
            [created_at] => 2018-06-21 17:33:45
            [updated_at] => 2018-06-21 17:33:45
            [subcat] => Array
                (
                    [0] => Array
                        (
                            [id] => 4
                            [category_name] => 要闻
                            [pid] => 3
                            [created_at] => 2018-06-21 17:33:55
                            [updated_at] => 2018-06-21 17:33:55
                        )

                    [1] => Array
                        (
                            [id] => 5
                            [category_name] => 企业服务
                            [pid] => 3
                            [created_at] => 2018-06-21 17:34:12
                            [updated_at] => 2018-06-21 17:34:12
                        )

                )

        )

    [1] => Array
        (
            [id] => 6
            [category_name] => 大新闻
            [pid] => 0
            [created_at] => 2018-06-26 14:41:28
            [updated_at] => 2018-06-26 14:41:28
            [subcat] => Array
                (
                    [0] => Array
                        (
                            [id] => 7
                            [category_name] => 优惠
                            [pid] => 6
                            [created_at] => 2018-06-26 14:41:45
                            [updated_at] => 2018-06-26 14:41:45
                        )

                )

        )

)
Array
(
    [0] => Array
        (
            [id] => 4
            [category_name] => 要闻
            [pid] => 3
            [created_at] => 2018-06-21 17:33:55
            [updated_at] => 2018-06-21 17:33:55
            [level] => 0
        )

    [1] => Array
        (
            [id] => 3
            [category_name] => 新闻
            [pid] => 0
            [created_at] => 2018-06-21 17:33:45
            [updated_at] => 2018-06-21 17:33:45
            [level] => 0
        )

    [2] => Array
        (
            [id] => 5
            [category_name] => 企业服务
            [pid] => 3
            [created_at] => 2018-06-21 17:34:12
            [updated_at] => 2018-06-21 17:34:12
            [level] => 0
        )

    [3] => Array
        (
            [id] => 6
            [category_name] => 大新闻
            [pid] => 0
            [created_at] => 2018-06-26 14:41:28
            [updated_at] => 2018-06-26 14:41:28
            [level] => 0
        )

    [4] => Array
        (
            [id] => 7
            [category_name] => 优惠
            [pid] => 6
            [created_at] => 2018-06-26 14:41:45
            [updated_at] => 2018-06-26 14:41:45
            [level] => 0
        )

)

 

微信小程序地图服务使用 百度坐标系经纬度 方法 百度坐标系转 GCJ02

微信小程序使用 百度地图提供的坐标进行定位的时候会造成位置偏移,究其原因是百度地图未使用常规的国测局坐标(火星坐标,GCJ02)、或WGS84坐标系 而使用了自己的坐标系 百度坐标系

会造成经纬度上的一公里左右的偏移。

但百度只提供 WGS84、GCJ02 坐标系转百度坐标系的接口,而未提供百度坐标系转 WGS84、GCJ02坐标系

互联网在线地图使用的坐标系:

火星坐标系:

  • iOS 地图(其实是高德)
  • Gogole地图
  • 搜搜、阿里云、高德地图

百度坐标系:

  • 当然只有百度地图

WGS84坐标系:

  • 国际标准,谷歌国外地图、osm地图等国外的地图一般都是这个

微信小程序使用百度坐标系经纬度的解决方式:

腾讯位置服务提供了 微信小程序 JavaScript SDK,可进行其他坐标系的逆向解析,包含以下坐标系转换至腾讯坐标系:

  • GPS坐标
  • sogou经纬度
  • baidu经纬度
  • mapbar经纬度
  • [默认]腾讯、google、高德坐标
  • sogou墨卡托

接口文档: http://lbs.qq.com/qqmap_wx_jssdk/method-reverseGeocoder.html

PHP 自定义函数 记录错误 / LOG日志到文件

public function log($res){
    $err_date = date("Ym", time());
    $address = '/error';
    if (!is_dir($address)) {
        mkdir($address, 0700, true);
    }
    $address = $address.'/'.$err_date . '_error.log';
    $error_date = date("Y-m-d H:i:s", time());
    if(!empty($_SERVER['HTTP_REFERER'])) {
        $file = $_SERVER['HTTP_REFERER'];
    } else {
        $file = $_SERVER['REQUEST_URI'];
    }
    if(is_array($res)) {
        $res_real = "$error_date\t$file\n";
        error_log($res_real, 3, $address);
        $res = var_export($res,true);
        $res = $res."\n";
        error_log($res, 3, $address);
    } else {
        $res_real = "$error_date\t$file\t$res\n";
        error_log($res_real, 3, $address);
    }
}

 

微信小程序 JavaScript 时间比较函数 JS 日期比较

// 时间比较函数
compareDate:function (startDate, endDate) {
  var arrStart = startDate.split("-");
  var startTime = new Date(arrStart[0], arrStart[1], arrStart[2]);
  var startTimes = startTime.getTime();
  var arrEnd = endDate.split("-");
  var endTime = new Date(arrEnd[0], arrEnd[1], arrEnd[2]);
  var endTimes = endTime.getTime();
  if(endTimes<startTimes) {
    return false;
  }
return true;
},

 

微信小程序实现点击滑动展开效果动画

js

let animationShowHeight = 300;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    animation: ''
  },
  // 下来
  btnClick: function () {
    var animation = wx.createAnimation({
      transformOrigin: "50% 50%",
      duration: 1000,
      timingFunction: "ease",
      delay: 0
    })
    this.animation = animation
    animation.translateY(animationShowHeight).step()
    this.setData({
      animation: animation.export(),
    })

  },
  // 上去
  btnClickTo: function () {
    var animation = wx.createAnimation({
      transformOrigin: "50% 50%",
      duration: 1000,
      timingFunction: "ease",
      delay: 0
    })
    this.animation = animation
    animation.translateY(0).step()
    this.setData({
      animation: animation.export(),
    })
  }  
})

wxml

<button type="primary" bindtap="btnClick"> 点我下去 </button>
<button type="primary" bindtap="btnClickTo"> 点我回去 </button>
<view class="body-view" animation="{{animation}}">
  <view>我一会就出来吓死你</view>
  <view>我一会就出来吓死你</view>
  <view>我一会就出来吓死你</view>
</view>

微信小程序 picker 组件,当  range 为 Object Array 类型时示例代码

微信小程序 picker 组件,当  range 为 Object Array 类型时

wxml:

<picker bindchange="bindPickerChange" value="{{index}}" range-key="name" range="{{objectArray}}">
    <view class="picker">
      当前选择:{{objectArray[index].name}}
    </view>
</picker>

js:

Page({
  data: {
    objectArray: [
      {
        id: 0,
        name: '美国'
      },
      {
        id: 1,
        name: '中国'
      },
      {
        id: 2,
        name: '巴西'
      },
      {
        id: 3,
        name: '日本'
      }
    ]
  },
  bindPickerChange: function(e) {
    console.log('picker发送选择改变,携带值为', e.detail.value)
    var index = e.detail.value;
    var currentId = this.data.objectArray[index].id; 
    this.setData({
      index: e.detail.value
    })
  }
})

 

微信小程序支付完成后回调通知数据 记录

<xml><appid><![CDATA[wxf2e83f1160dfcxxx]]></appid><bank_type><![CDATA[ICBC_DEBIT]]></bank_type>/<cash_fee><![CDATA[1]]></cash_fee>/<fee_type><![CDATA[CNY]]></fee_type>/<is_subscribe><![CDATA[N]]></is_subscribe>/<mch_id><![CDATA[130xxx8601]]></mch_id>/<nonce_str><![CDATA[LhpVcEPpTNASOaQysNFNlYLrpMgyWDLa]]></nonce_str>/<openid><![CDATA[oC7xr5TZehbHbe__UUNPJzDapxxx]]></openid>/<out_trade_no><![CDATA[1528360591]]></out_trade_no>/<result_code><![CDATA[SUCCESS]]></result_code>/<return_code><![CDATA[SUCCESS]]></return_code>/<sign><![CDATA[766868113312ED3C141BF3D3487D1BDF]]></sign>/<time_end><![CDATA[20180607163654]]></time_end>/<total_fee>1</total_fee>/<trade_type><![CDATA[JSAPI]]></trade_type>/<transaction_id><![CDATA[4200000123201806075922186660]]></transaction_id>/</xml>

{"appid":"wxf2e83f1160dfcxxx","bank_type":"ICBC_DEBIT","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"130xxx8601","nonce_str":"yHbHrfbyDnWvRuogoOLWffsuFEXhDBeT","openid":"oC7xr5TZehbHbe__UUNPJzDapxxx","out_trade_no":"1528361071","result_code":"SUCCESS","return_code":"SUCCESS","sign":"364C903E8668AE6B49A1EE2B7A217D97","time_end":"20180607164442","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200000126201806078162413986"}

接收并处理

$data['postStr']=isset($GLOBALS['HTTP_RAW_POST_DATA']) ? $GLOBALS['HTTP_RAW_POST_DATA'] : file_get_contents("php://input");
$postdata = json_decode(json_encode(simplexml_load_string($data['postStr'], 'SimpleXMLElement', LIBXML_NOCDATA)), true);

JSON格式化

{
    "appid": "wxf2e83f1160dfcxxx",
    "bank_type": "ICBC_DEBIT",
    "cash_fee": "1",
    "fee_type": "CNY",
    "is_subscribe": "N",
    "mch_id": "130xxx8601",
    "nonce_str": "yHbHrfbyDnWvRuogoOLWffsuFEXhDBeT",
    "openid": "oC7xr5TZehbHbe__UUNPJzDapxxx",
    "out_trade_no": "1528361071",
    "result_code": "SUCCESS",
    "return_code": "SUCCESS",
    "sign": "364C903E8668AE6B49A1EE2B7A217D97",
    "time_end": "20180607164442",
    "total_fee": "1",
    "trade_type": "JSAPI",
    "transaction_id": "4200000126201806078162413986"
}

官方文档:https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_7&index=8

微信小程序支付 记录

private $appid  = "" ;
private $secret = "";
private $mch_id = '';
private $key = '';
private $openid = '';
public function index(){
    $this->load->library('wxpay');

    $code = $this->input->post("code");
    $total_fee = $this->input->post("total_fee");
    $total_fee = $total_fee?:1;

    //获取openid
    if($code)
    {
        $WX_APPID = $this->appid;
        $WX_SECRET = $this->secret;
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $WX_APPID . "&secret=" . $WX_SECRET . "&js_code=" . $code . "&grant_type=authorization_code";
        $infos = json_decode(file_get_contents($url));
        $openid = $infos->openid;
    }
    if(!$openid){
        $openid = $this->openid();
    }

    $appid =        $this->appid;//如果是公众号 就是公众号的appid
    $body =         '小程序支付';
    $mch_id =       $this->mch_id;
    $nonce_str =    $this->nonce_str();//随机字符串
    $notify_url =   'test';
    $openid =      $openid;
    $out_trade_no = time();//商户订单号
    $spbill_create_ip = '127.0.0.1';
    $total_fee =    $total_fee;//因为充值金额最小是1 而且单位为分 如果是充值1元所以这里需要*100
    $trade_type = 'JSAPI';//交易类型 默认


    //这里是按照顺序的 因为下面的签名是按照顺序 排序错误 肯定出错
    $post['appid'] = $appid;
    $post['body'] = $body;
    $post['mch_id'] = $mch_id;
    $post['nonce_str'] = $nonce_str;//随机字符串
    $post['notify_url'] = $notify_url;
    $post['openid'] = $openid;
    $post['out_trade_no'] = $out_trade_no;
    $post['spbill_create_ip'] = $spbill_create_ip;//终端的ip
    $post['total_fee'] = $total_fee;//总金额 最低为一块钱 必须是整数
    $post['trade_type'] = $trade_type;
    $sign = $this->sign($post);//签名
    
    $post_xml = '<xml>
           <appid>'.$appid.'</appid>
           <body>'.$body.'</body>
           <mch_id>'.$mch_id.'</mch_id>
           <nonce_str>'.$nonce_str.'</nonce_str>
           <notify_url>'.$notify_url.'</notify_url>
           <openid>'.$openid.'</openid>
           <out_trade_no>'.$out_trade_no.'</out_trade_no>
           <spbill_create_ip>'.$spbill_create_ip.'</spbill_create_ip>
           <total_fee>'.$total_fee.'</total_fee>
           <trade_type>'.$trade_type.'</trade_type>
           <sign>'.$sign.'</sign>
        </xml> ';
    //统一接口prepay_id
    $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';
    $xml = $this->http_request($url,$post_xml);

    $array = $this->xml($xml);//全要大写
    if($array['RETURN_CODE'] == 'SUCCESS' && $array['RESULT_CODE'] == 'SUCCESS'){
        $time = time();
        $tmp='';//临时数组用于签名
        $tmp['appId'] = $appid;
        $tmp['nonceStr'] = $nonce_str;
        $tmp['package'] = 'prepay_id='.$array['PREPAY_ID'];
        $tmp['signType'] = 'MD5';
        $tmp['timeStamp'] = "$time";
        $data['state'] = 1;
        $data['timeStamp'] = "$time";//时间戳
        $data['nonceStr'] = $nonce_str;//随机字符串
        $data['signType'] = 'MD5';//签名算法,暂支持 MD5
        $data['package'] = 'prepay_id='.$array['PREPAY_ID'];//统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=*
        $data['paySign'] = $this->sign($tmp);//签名,具体签名方案参见微信公众号支付帮助文档;
        $data['out_trade_no'] = $out_trade_no;


    }else{
        $data['state'] = 0;
        $data['text'] = "错误";
        $data['RETURN_CODE'] = $array['RETURN_CODE'];
        $data['RETURN_MSG'] = $array['RETURN_MSG'];
    }
    echo json_encode($data); //小程序需要的数据 返回前端

}

public function sign($data){
    $stringA = '';
    foreach ($data as $key=>$value){
        if(!$value) continue;
        if($stringA) $stringA .= '&'.$key."=".$value;
        else $stringA = $key."=".$value;
    }
    $wx_key = $this->key;//申请支付后有给予一个商户账号和密码,登陆后自己设置key
    $stringSignTemp = $stringA.'&key='.$wx_key;//申请支付后有给予一个商户账号和密码,登陆后自己设置key
    return strtoupper(md5($stringSignTemp));
}

public function nonce_str(){
    $result = '';
    $str = 'QWERTYUIOPASDFGHJKLZXVBNMqwertyuioplkjhgfdsamnbvcxz';
    for ($i=0;$i<32;$i++){
        $result .= $str[rand(0,48)];
    }
    return $result;
}

function http_request($url,$data = null,$headers=array())
{
    $curl = curl_init();
    if( count($headers) >= 1 ){
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($curl, CURLOPT_URL, $url);


    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);


    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

private function xml($xml){
    $p = xml_parser_create();
    xml_parse_into_struct($p, $xml, $vals, $index);
    xml_parser_free($p);
    $data = "";
    foreach ($index as $key=>$value) {
        if($key == 'xml' || $key == 'XML') continue;
        $tag = $vals[$value[0]]['tag'];
        $value = $vals[$value[0]]['value'];
        $data[$tag] = $value;
    }
    return $data;
}
payStart:function(){
    var total_fee = total_fee; 
    wx.login({
      success: res => {  
         //code 用于获取openID的条件之一
        var code = res.code;
        wx.request({
          url: 'http://xxx/xx/x',
          method: "POST",
          data: {
            total_fee:2,
            code: code,
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded' // 默认值
          },
          success: function (res) {  //后端返回的数据
            var data = res.data;
            console.log(data);
            console.log(data["timeStamp"]);
            wx.requestPayment({
              timeStamp: data['timeStamp'],
              nonceStr: data['nonceStr'],
              package: data['package'],
              signType: data['signType'],
              paySign: data['paySign'],
              success: function (res) {
                wx.showModal({
                  title: '支付成功',
                  content: '',
                })
              },
              fail: function (res) {
                console.log(res);
              }
            })
          }
        }); 
      }
    })
  }