分类 PHP 下的文章

  • array_diff_assoc2
array_diff_assoc 在比对两个带key的数组时, 如果右边的数组没有对应的key, 左边对应的key是数组, 那没事, 不然就会转换左边的内容为字符串带来警告
function array_diff_assoc2($array, $array2)
{
    $d = [];
    foreach ($array as $key => $item) {
        if (array_key_exists($key, $array2)) {
            if (is_array($item)) {
                if (is_array($array2[$key])) {
                    if ($item != $array2[$key]) {
                        $d[$key] = $item;
                    }
                } else if (
                    (strpos($array2[$key], '[') === false 
                        && strpos($array2[$key], '{') === false)
                    || $item != json_decode($array2[$key], true)
                ) {
                    $d[$key] = $item;
                }
            } else if (is_array($array2[$key])) {
                if ($item != json_encode($array2[$key], 256)) {
                    $d[$key] = $item;
                }
            } else if ($item . '' != $array2[$key] . '') {
                $d[$key] = $item;
            }
        } else {
            $d[$key] = $item;
        }
    }
    return $d;
}
  • json_encode [php特殊环境下无法使用该方法的过度办法]
function json_encodes($arr)
{
    $parts = array();
    $is_list = false;
    //Find out if the given array is a numerical array
    if (is_array($arr)) {
        $keys = array_keys($arr);
        $max_length = count($arr) - 1;
        if (
            !is_null($keys)
            && array_key_exists('0', $keys)
            && ($keys [0] === 0)
            && ($keys [$max_length] === $max_length)) { //See if the first key is 0 and last key is length - 1
            $is_list = true;
            for ($i = 0; $i < count($keys); $i++) { //See if each key correspondes to its position
                if ($i != $keys [$i]) { //A key fails at position check.
                    $is_list = false; //It is an associative array.
                    break;
                }
            }
        }
        foreach ($arr as $key => $value) {
            if (is_array($value)) { //Custom handling for arrays
                if ($is_list)
                    $parts [] = json_encodes($value); /* :RECURSION: */
                else
                    $parts [] = '"' . $key . '":' . json_encodes($value); /* :RECURSION: */
            } else {
                $str = '';
                if (!$is_list)
                    $str = '"' . $key . '":';
                //Custom handling for multiple data types
                if (is_numeric($value) && $value === $value * 1) {
                    $str .= $value;
                } elseif ($value === false)
                    $str .= 'false'; //The booleans
                elseif ($value === true)
                    $str .= 'true';
                elseif ($value === null)
                    $str .= 'null';
                else
                    $str .= '"' . addslashes($value) . '"'; //All other things
                // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
                if (is_string($str)) {
                    $str = str_replace(PHP_EOL, '\r\n', $str);
                }
                $parts [] = $str;
            }
        }
    }

    $json = implode(',', $parts);
    if ($is_list)
        return '[' . $json . ']'; //Return numerical JSON
    return '{' . $json . '}'; //Return associative JSON
}

情况是这样的, 用php写了个身份证签到客户端, 网页打开当前页面, 搜索传递的中文传递给本地程序, 本地程序在转换后发送给真实的接口, 其中中文名搜索出现了点小尴尬

本地客户端php就写了几个php文件, 接受参数都是直接用的 $_REQUEST['search_value'] 接收, 直接var_dump() 可以正常打印中文名, 但是转发请求调用接口就不行了, 且接收端做了处理了, 比如对收到的参数执行了 urldecode() 

后来问题还是解决了, 本地的php发放在转发参数值, 需要将中文参数执行 urlencode() 对应的参数值即可

九宫格切割以及加文字方法

!defined('BASE_PATH') && define('BASE_PATH', dirname(__DIR__, 1));
define('CACHE_PATH', BASE_PATH . '/runtime/cache');
define('RESOURCE_PATH', BASE_PATH . '/resource');

// 九宫格切图且添加文字
imageSlicing9($imgPath, $fonts = [], $fontPath = null)
{
    list($width, $height) = getimagesize($imgPath);
    $source = imagecreatefromjpeg($imgPath);

    $width = $width - $width % 3;
    $height = $height - $height % 3;

    $baseWidth = $width / 3;
    $baseHeight = $height / 3;;

    $imgPathMd5 = md5($imgPath);
    $results = [];
    foreach ([
                 [0, 0],
                 [$baseWidth, 0],
                 [$baseWidth * 2, 0],

                 [0, $baseHeight],
                 [$baseWidth, $baseHeight],
                 [$baseWidth * 2, $baseHeight],

                 [0, $baseHeight * 2],
                 [$baseWidth, $baseHeight * 2],
                 [$baseWidth * 2, $baseHeight * 2],
             ] as $key => $item) {
        $thumb = ImageCreateTrueColor($baseWidth, $baseHeight);
        imagecopyresized($thumb, $source, 0, 0, $item[0], $item[1], $baseWidth, $baseHeight, $baseWidth, $baseHeight);

        if (!empty($fonts[$key])) {

            $fontCount = mb_strlen($fonts[$key], 'utf-8');
            $black = imagecolorallocate($thumb, 0, 0, 0);//字体颜色 RGB
            $fontSize = 12;   //字体大小

            $circleSize = 0; //旋转角度
            $left = 5;
            $right = 5;
            $fonttIndex = 0;
            $fontList = [];
            $fonttRowWidth = $baseWidth - $left - $right;
            $fontList[$fonttIndex] = '';
            $fontListWidth[$fonttIndex] = 0;
            $fonttHeight = $fontSize;
            for ($iii = 0; $iii < $fontCount; $iii++) {
                $fontt = mb_substr($fonts[$key], $iii, 1, 'utf-8');
                $pos = imagettfbbox($fontSize, 0, $fontPath, $fontt);
                $fonttWidth = $pos[2] - $pos[0];
                $fonttHeight = $pos[3] - $pos[5];
                // 计算剩余宽度, 如果够, 那么就挤进去, 否则下一排
                if (($fonttRowWidth = $fonttRowWidth - $fonttWidth) > 0) {
                    $fontList[$fonttIndex] .= $fontt;
                    $fontListWidth[$fonttIndex] += $fonttWidth;
                } else {
                    $fonttRowWidth = $baseWidth - $left - $right - $fonttWidth;
                    $fonttIndex++;
                    $fontList[$fonttIndex] = $fontt;
                    $fontListWidth[$fonttIndex] = $fonttWidth;
                }
            }
            $top = $baseHeight - ($fonttHeight + 5) * count($fontList) + 5;
            if ($top < 0) {
                $top = 10;
            }
            if (count($fontList) == 1) {
                $left = intval(($baseWidth - $fontListWidth[0]) / 2);
            }
            foreach ($fontList as $fontvalue) {
                imagefttext($thumb, $fontSize, $circleSize, $left, $top, $black, $fontPath, $fontvalue);
                $top = $top + $fonttHeight + 5;
            }


            /*
            $widthFonts = intval($baseWidth / ($fontSize * 1.4)); // 一排显示的文字数量
            $rows = ceil($fontCount / $widthFonts);
            $top = $baseHeight - ($fontSize + 5) * $rows;
            if ($top < 0) {
                $top = 0;
            }
            for ($ii = 1; $ii <= $rows; $ii++) {
                // $fontItem = substr($fonts[$key], ($ii - 1) * $widthFonts, $widthFonts);
                $fontItem = mb_substr($fonts[$key], ($ii - 1) * $widthFonts, $widthFonts, 'utf-8');
                if (!empty($fontItem)) {
                    var_dump([$left, $top, $fontItem]);
                    imagefttext($thumb, $fontSize, $circleSize, $left, $top, $black, $fontPath, $fontItem);
                }
                $top = $top + $fontSize + 5;
            }
            */
        }

        imagejpeg($thumb, $results[] = CACHE_PATH . "/" . $imgPathMd5 . "{$key}.jpg", 100);
    }
    return $results;
}

执行图片切割且加文字

$imgPath = BASE_PATH . '/runtime/cache/timg.jpg';
$fontPath = RESOURCE_PATH . '/fonts/方正黑体简体.TTF';//字体,字体文件需保存到相应文件夹下
$fonts = ["啊1","啊2","啊3","啊4","啊5","啊6","啊7","啊8","啊9",]
$pp = imageSlicing9($imgPath, $fonts, $fontPath);
var_dump($pp);

模型列表自动Where

if (!function_exists('model_where')) {
    function model_where(&$model, $where)
    {
        if (empty($where)) {
            return $model;
        }
        // 使用表结构分析, 自动将传进来的参数根据分析的表结构来决定查询条件
        $tableInfo = $model::DB()->select('SHOW FULL FIELDS FROM `' . $model->getTable() . '`');
        $tableInfo = object_to_array($tableInfo);
        $tableInfo = array_column_to_key($tableInfo, 'Field');
        $model = $model::query();
        foreach ($tableInfo as $key => $v) {
            if (strpos($tableInfo[$key]['Type'], 'int') !== false) {
                if (array_key_exists($key, $where) && is_numeric($where[$key])) {
                    $model = $model->where($key, intval($where[$key]));
                }
            } else if (strpos($tableInfo[$key]['Type'], 'char') !== false) {
                if (!empty($where[$key])) {
                    $model = $model->where($key, 'like', '%' . $where[$key] . '%');
                }
            } else if (
                strpos($tableInfo[$key]['Type'], 'decimal') !== false
                || strpos($tableInfo[$key]['Type'], 'timestamp') !== false
            ) {
                if (array_key_exists($key . '_from', $where) && $where[$key . '_from'] !== '') {
                    $model = $model->where($key, '>=', $where[$key . '_from']);
                }
                if (array_key_exists($key . '_to', $where) && $where[$key . '_to'] !== '') {
                    $model = $model->where($key, '<', $where[$key . '_to']);
                }
                if (array_key_exists($key, $where) && $where[$key] !== '') {
                    $model = $model->where($key, $where[$key]);
                }
            } else if (strpos($tableInfo[$key]['Type'], 'enum') !== false) {
                if (array_key_exists($key, $where)) {
                    $model = $model->where($key, $where[$key]);
                }
            }
        }
    }
}
  • 代码层使用示例
$where = RequestHelper::get();
$query = new AbcdModel()
model_where($query,$where);
return ResponseHelper::paginator($query->paginate(RequestHelper::getPerPage()), new \App\Transformers\AbcdModelTransformer());

限制不重复写入

if (!function_exists('sql_insert_once')) {
    // 写入限制, 确保写入只会被写入一次
    function model_sql_insert_once($table, $array, $existsSql = '')
    {
        $sql0 = [];
        $sql1 = [];
        foreach ($array as $kq => $kv) {
            $sql0[] = '`' . $kq . '`';
            if (is_null($kv)) {
                $sql1[] = 'NULL';
            } else {
                $sql1[] = '\'' . addslashes($kv) . '\'';
            }
        }
        // SELECT * FROM `' . $table . '` WHERE AND created_at>NOW()-INTERVAL 5 SECOND
        return ' INSERT INTO `' . $table . '`(' . implode(',', $sql0) . ') 
 SELECT ' . implode(',', $sql1) . ' FROM DUAL WHERE NOT EXISTS(' . $existsSql . ') ';

        /*
        DB::insert(DB::raw($tmpSql));
        $paymentParentId = DB::getPdo()->lastInsertId();
        if (empty($paymentParentId)) {
            error_responses('支付中 ...');
        }
        */

    }
}
  • 使用demo
$sql = model_sql_insert_once('course_orders', $courseOrderHeader, "SELECT * FROM course_orders WHERE 
help_code='" . $courseOrderHeader['help_code'] . "'
AND pid='" . $courseOrderHeader['pid'] . "'
AND class_id='" . $courseOrderHeader['class_id'] . "'
AND course_id='" . $courseOrderHeader['course_id'] . "'
AND state=1
AND created_at>NOW()-INTERVAL 60 SECOND");
// DB::insert(DB::raw($sql)) ;
$db = CourseOrderItem::DB();
$db->beginTransaction();
$db->insert($sql);
$orderId = DB::getPdo()->lastInsertId();
if (empty($orderId)){
    error_response('下单中');
}