首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 常用基礎函數大全:16 個實用代碼片段收藏

     編輯:PHP 綜合知識

陣列與數據處理

1. 統計多維陣列元素出現次數

$arr = ['1011,1003,1008', '1009', '1011,1003,1111'];
$result = [];
foreach ($arr as $str) {
    foreach (explode(',', $str) as $v) {
        $result[$v] = ($result[$v] ?? 0) + 1;
    }
}
// 結果: [1011=>2, 1003=>2, 1008=>1, ...]

2. 遞歸刪除目錄

function cleanup_directory($dir) {
    foreach (new DirectoryIterator($dir) as $file) {
        if ($file->isDir() && !$file->isDot()) {
            cleanup_directory($file->getPathname());
        } elseif (!$file->isDir()) {
            unlink($file->getPathname());
        }
    }
    rmdir($dir);
}

3. 無限級分類生成樹(兩種實現)

// 方法一:引用構建
function generateTree($items) {
    $tree = [];
    foreach ($items as $item) {
        if (isset($items[$item['pid']])) {
            $items[$item['pid']]['son'][] = &$items[$item['id']];
        } else {
            $tree[] = &$items[$item['id']];
        }
    }
    return $tree;
}

// 方法二:鍵值映射(更快)
function generateTree2($items) {
    foreach ($items as $item) 
        $items[$item['pid']]['son'][$item['id']] = &$items[$item['id']];
    return $items[0]['son'] ?? [];
}

4. 陣列排序:數值與字符串統一寫法

$test = ['ab', 'ac', 'bd', 'bc'];
usort($test, fn($a, $b) => $a <=> $b);  // PHP 7+ 太空船操作符
// 或兼容寫法
usort($test, function($a, $b) {
    return ($a < $b) ? -1 : (($a > $b) ? 1 : 0);
});

5. array_reduce 構建鍵值映射

$raw = [1,2,3,4,5];
$result = array_reduce($raw, fn($carry, $v) => ($carry[$v] = $v, $carry), []);
// [1=>1, 2=>2, 3=>3, 4=>4, 5=>5]

6. array_map 多陣列並行處理

$input = ['key' => 'value'];
array_map(fn($k, $v) => print($k.$v), array_keys($input), $input);
// 輸出: keyvalue

$double = fn($x) => 2 * $x;
array_map($double, [1,2,3]); // [2, 4, 6]

算法與邏輯

7. 斐波那契數列(兔子繁殖)

$month = 12;
$fab = [1, 1];
for ($i = 2; $i < $month; $i++) 
    $fab[$i] = $fab[$i-1] + $fab[$i-2];

日期時間處理

8. 獲取月首/末日期

function getCurMonthFirstDay($date) {
    return date('Y-m-01', strtotime($date));
}
function getCurMonthLastDay($date) {
    return date('Y-m-d', strtotime('+1 month -1 day', strtotime(date('Y-m-01', strtotime($date)))));
}

加密與安全

9. 簡易對稱加密解密

function encrypt($data, $key) {
    $key = md5($key);
    $str = '';
    for ($i=0, $x=0, $len=strlen($data); $i<$len; $i++) {
        $x = $x == strlen($key) ? 0 : $x;
        $str .= chr(ord($data[$i]) + ord($key[$x++]) % 256);
    }
    return base64_encode($str);
}

function decrypt($data, $key) {
    $key = md5($key);
    $data = base64_decode($data);
    $str = '';
    for ($i=0, $x=0, $len=strlen($data); $i<$len; $i++) {
        $x = $x == strlen($key) ? 0 : $x;
        $d = ord($data[$i]); $k = ord($key[$x++]);
        $str .= chr($d < $k ? $d + 256 - $k : $d - $k);
    }
    return $str;
}

陣列進階

10. 多維陣列扁平化

function array_flatten($arr) {
    $result = [];
    array_walk_recursive($arr, fn($v) => $result[] = $v);
    return $result;
}
// [1,[2,3],[4,5]] => [1,2,3,4,5]

11. 二維陣列去重(保留鍵名)

function about_unique($arr) {
    $keys = array_keys($arr[0]);
    $temp = array_map(fn($v) => implode(',', $v), $arr);
    $temp = array_unique($temp);
    $temp = array_map(fn($v) => explode(',', $v), $temp);
    foreach ($temp as $k => $v)
        foreach ($v as $kk => $cv)
            $data[$k][$keys[$kk]] = $cv;
    return $data;
}

工具函數

12. 格式化字節大小

function format_bytes($size, $delimiter = '') {
    $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
    for ($i = 0; $size >= 1024 && $i < 6; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

13. 相對時間(如「3分鐘前」)

function time_ago($timestamp) {
    $etime = time() - $timestamp;
    if ($etime < 1) return '剛剛';
    $intervals = [
        3600*24*30*12 => '年前', 3600*24*30 => '個月前',
        3600*24*7 => '周前', 3600*24 => '天前',
        3600 => '小時前', 60 => '分鐘前', 1 => '秒前'
    ];
    foreach ($intervals as $secs => $str) 
        if (($d = $etime / $secs) >= 1) return round($d) . $str;
}

14. 身份證驗證(含地址碼、出生日期、校驗碼)

function is_citizen_id($id) {
    $id = strtoupper($id);
    if (!preg_match('/^\d{17}[\dX]$/', $id) && !preg_match('/^\d{15}$/', $id)) 
        return false;
    // ... 完整校驗邏輯(權重因子、校驗碼、地址碼、日期合法性)
    return ['id'=>$id, 'location'=>$city, 'birth'=>$birth, 'sex'=>$sex];
}

15. 獲取二維陣列指定列集合

$ids = array_column($users, 'id');           // PHP 5.5+
$names = array_column($users, 'name', 'id');  // 以 id 為鍵

16. JSON 中文不轉義

function json_encode_wrapper($data) {
    if (defined('JSON_UNESCAPED_UNICODE')) 
        return json_encode($data, JSON_UNESCAPED_UNICODE | JSON_NUMERIC_CHECK);
    return preg_replace_callback('#\\\u([0-9a-f]{4})#i', 
        fn($m) => iconv('UCS-2BE', 'UTF-8', pack('H4', $m[1])), 
        json_encode($data));
}

總結

這 16 個片段覆蓋了 PHP 開發中 80% 的高頻場景。建議整理為項目公共庫(如 `Common/Functions.php`),按模組引入,避免重複造輪子。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved