Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial 分享一个函数,求bug,求改进^_^

分享一个函数,求bug,求改进^_^

Jun 23, 2016 pm 01:44 PM

我们phper经常会用到很多对数字或字符串的处理函数
遗憾的是大部分都不支持数组
灵光一闪,搞定它
觉得有用的大大们捧个场
顺便找些bug并给些改进的建议

/** * 通过递归调用让函数支持多维数组 by wanderwind * 建议其他函数调用来实现 * @param string $fn 调用函数名称 * @param array $param 参数数组,通常传入func_get_args() * @param int $key 需要递归的参数键值 * @param boolean $check 是否需要检测函数合法性 * @return mixed 返回对$param[$key]的运行结果 */function fn2array($fn, $param, $key = 0, $check = true) {    //从外部调用时默认检测函数合法性,多维数组递归时忽略    if ($check && !function_exists($fn)) {        return false;    }    //提取执行目标,如果目标非数组可以直接执行    $content = $param[$key];    if (!is_array($content)) {        return call_user_func_array($fn, $param);    }    //如果目标是数组则递归执行    foreach ($content as &$val) {        $param[$key] = $val;        $val = fn2array($fn, $param, $key, false);    }    return $content;}function wstripslashes() {    return fn2array('stripslashes', func_get_args());}function wsubstr() {    $param = func_get_args();    $param[3] = isset($param[3]) ? $param[3] : 'utf-8';    return fn2array('mb_substr', $param, 0);}$a = array(    2 => '\"aaaaaaaaaaaaaaa\"',    array('\"啊啊啊啊啊啊啊啊啊啊啊啊啊\"'),    array(array(array('\"sss\dasf\dasfasdsad\"'))),);print_r(wstripslashes($a));print_r(wsubstr($a, 2, 5));
Copy after login


回复讨论(解决方案)

发完帖子想到一个改进方向,例如我们经常从数据库筛选出一个结果集数组,可能需要单独对某几个字段过滤
例如对title和content单独进行stripslashes
接口可以设计为 wstripslashes($data, 'title,content')
这样的话需要多一步对键值的判定

您忘了 php 的 array_walk_recursive 函数

您忘了 php 的 array_walk_recursive 函数



确实有个不爱看手册的坏毛病
但是刚刚翻了一下,我粗浅的觉得这个函数可能无法满足需求
1,如何支持多维数组?
2,如何用它递归iconv('gbk', 'utf-8', $str)这种函数?
因为没使用过这个函数,可能需要麻烦斑竹写个示例

$ar = array(  array('汉字'),  array('汉字'),  array(    array('汉字'),    array('汉字'),    array(      array('汉字'),      array('汉字'),    ),  ),);function zm(&$v, $k, $charset) {  $v = iconv($charset[0], $charset[1], $v);}array_walk_recursive($ar, 'zm', array('gbk', 'utf-8'));print_r($ar);
Copy after login
Copy after login

??支持下。

$ar = array(  array('汉字'),  array('汉字'),  array(    array('汉字'),    array('汉字'),    array(      array('汉字'),      array('汉字'),    ),  ),);function zm(&$v, $k, $charset) {  $v = iconv($charset[0], $charset[1], $v);}array_walk_recursive($ar, 'zm', array('gbk', 'utf-8'));print_r($ar);
Copy after login
Copy after login



感谢xu大,又学到东西了
用系统提供的函数或许性能会强一些
但结合开发体验,我还是想支持自己的方法
array_walk_recursive对原数据是引用,而且参数传递方法比较死,如果想不污染$ar,同时让开发者使用便利,就要再定义一个函数

function zm(&$v, $k, $charset) {    $v = iconv($charset[0], $charset[1], $v);}function wiconv($in, $out, $content) {    array_walk_recursive($content, 'zm', array($in, $out));    return $content;}
Copy after login


其实这样的wiconv也不行,还要加入$content本身就是字符串的判定条件~
我是希望有一种快速创建新函数,并且不改变原函数使用习惯的方法,貌似有点面向对象的继承思想?
比如我的方法中 iconv可以这样扩展:
function wiconv() {    //2代表递归第三个参数是目标    return fn2array('iconv', func_get_args(), 2);}$ar = array('汉字', array(array('汉字')));print_r(wiconv('utf-8', 'gbk', $ar));    //不改变原函数使用习惯
Copy after login


您觉得呢

??支持下。



function wiconv($in_charset, $out_charset, $str) {  if(is_array($str)) {    array_walk_recursive($str,      function(&$v, $k, $p) {        $v = iconv($p[0], $p[1], $v);      }, array($in_charset, $out_charset));    return $str;  }  return iconv($in_charset, $out_charset, $str);}
Copy after login

又想起了那句著名的话:重复造轮子的人呐

不是很明白函数的意思,不过还是进来看看

又想起了那句著名的话:重复造轮子的人呐



前人的轮子不好,咱就努力造个更好的,即便实际做出来很糟糕,这也是造出更好轮子的第一步~你说呢

造轮子没有什么不好,选好材料和工艺才能事半功倍

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles