search

php数组工具类

PHP二维数组去重复项函数

<?phpfunction unique_array_2d($array2D,$stkeep=false,$ndformat=true){	// 判断是否保留一级数组键 (一级数组键可以为非数字)	if($stkeep) $stArr = array_keys($array2D);	// 判断是否保留二级数组键 (所有二级数组键必须相同)	if($ndformat) $ndArr = array_keys(end($array2D));	//降维,也可以用implode,将一维数组转换为用逗号连接的字符串	foreach ($array2D as $v){		$v = join(",",$v); 		$temp[] = $v;	}	//去掉重复的字符串,也就是重复的一维数组	$temp = array_unique($temp); 	//再将拆开的数组重新组装	foreach ($temp as $k => $v)	{		if($stkeep) $k = $stArr[$k];		if($ndformat)		{			$tempArr = explode(",",$v); 			foreach($tempArr as $ndkey => $ndval) $output[$k][$ndArr[$ndkey]] = $ndval;		}		else $output[$k] = explode(",",$v); 	}	return $output;}$array2D = array(	'first'=>array('title'=>'1111','date'=>'2222'),	'second'=>array('title'=>'1111','date'=>'2222'),	'third'=>array('title'=>'2222','date'=>'3333'));echo "<pre class="brush:php;toolbar:false">";print_r(unique_array_2d($array2D,true));/*** 将二维数组通过指定的 key 去重** @param array $arr 要去重的数组* @param array $by  指定key去重,该参数不指定将返回 array()* @return array*/function array_multunique($arr,$by = array()) {	$temp = array();	foreach($arr as $key => $val) {		foreach($by as $v) {			$temp[$key] .= isset($val[$v]) ? $val[$v] : '';		}	}	return array_intersect_key($arr,array_unique($temp));}/*$aa = array (      array ('id' => 123, 'name' => '张三' ),       array ('id' => 123, 'name' => '李四' ),       array ('id' => 124, 'name' => '王五' ),       array ('id' => 125, 'name' => '赵六' ),       array ('id' => 126, 'name' => '赵六' )   );  $key = 'id';  array_multunique ($aa, array('id')); */function array_remove_key($array,$keys){	if (!is_array($array) || !is_array($keys)){		return false;	}	foreach($array as $t){		foreach($keys as $k){			unset($t[$k]);		}		$doc[]=$t;	}	return $doc;}/*$array = array(	'0' => array('a' => 'aaaaa', 'b' => 'bbbbb', 'c' => array('d' => 'ddddd', 'e' => 'eeeee')),	'1' => array('a' => 'aaaaa', 'b' => 'bbbbb', 'c' => array('d' => 'ddddd', 'e' => 'eeeee')));print_r( array_remove_key($array,array('c')));*/function array_remove_key_val(&$a,$b,$c){	foreach ($a as $key=>$value){		if ( isset($value[$b]) && ($value[$b]==$c) ){			unset($a[$key]);		}	}}/*$a=array(	array('id'=>1,'num'=>10,'type'=>'news'),	array('id'=>2,'num'=>100,'type'=>'pic'));print_r( array_remove_key_val($a,"id","1") );*/

数组xml 相互转换http://hudeyong926.iteye.com/blog/836048

<?php/** * 从数组中删除空白的元素(包括只有空白字符的元素) * * @param array $arr * @param boolean $trim */function array_remove_empty(& $arr, $trim = true){    foreach ($arr as $key => $value) {        if (is_array($value)) {            array_remove_empty($arr[$key]);        } else {            $value = trim($value);            if ($value == '') {                unset($arr[$key]);            } elseif ($trim) {                $arr[$key] = $value;            }        }    }}/** * 从一个二维数组中返回指定键的所有值 * * @param array $arr * @param string $col * * @return array */function array_col_values(& $arr, $col){    $ret = array();    foreach ($arr as $row) {        if (isset($row[$col])) { $ret[] = $row[$col]; }    }    return $ret;}/** * 将一个二维数组转换为 hashmap * * 如果省略 $valueField 参数,则转换结果每一项为包含该项所有数据的数组。 * * @param array $arr * @param string $keyField * @param string $valueField * * @return array */function array_to_hashmap(& $arr, $keyField, $valueField = null){    $ret = array();    if ($valueField) {        foreach ($arr as $row) {            $ret[$row[$keyField]] = $row[$valueField];        }    } else {        foreach ($arr as $row) {            $ret[$row[$keyField]] = $row;        }    }    return $ret;}/** * 将一个二维数组按照指定字段的值分组 * * @param array $arr * @param string $keyField * * @return array */function array_group_by(& $arr, $keyField){    $ret = array();    foreach ($arr as $row) {        $key = $row[$keyField];        $ret[$key][] = $row;    }    return $ret;}/** * 将一个平面的二维数组按照指定的字段转换为树状结构 * * 当 $returnReferences 参数为 true 时,返回结果的 tree 字段为树,refs 字段则为节点引用。 * 利用返回的节点引用,可以很方便的获取包含以任意节点为根的子树。 * * @param array $arr 原始数据 * @param string $fid 节点ID字段名 * @param string $fparent 节点父ID字段名 * @param string $fchildrens 保存子节点的字段名 * @param boolean $returnReferences 是否在返回结果中包含节点引用 * * return array */function array_to_tree($arr, $fid, $fparent = 'parent_id',    $fchildrens = 'childrens', $returnReferences = false){    $pkvRefs = array();    foreach ($arr as $offset => $row) {        $pkvRefs[$row[$fid]] =& $arr[$offset];    }    $tree = array();    foreach ($arr as $offset => $row) {        $parentId = $row[$fparent];        if ($parentId) {            if (!isset($pkvRefs[$parentId])) { continue; }            $parent =& $pkvRefs[$parentId];            $parent[$fchildrens][] =& $arr[$offset];        } else {            $tree[] =& $arr[$offset];        }    }    if ($returnReferences) {        return array('tree' => $tree, 'refs' => $pkvRefs);    } else {        return $tree;    }}/** * 将树转换为平面的数组 * * @param array $node * @param string $fchildrens * * @return array */function tree_to_array(& $node, $fchildrens = 'childrens'){    $ret = array();    if (isset($node[$fchildrens]) && is_array($node[$fchildrens])) {        foreach ($node[$fchildrens] as $child) {            $ret = array_merge($ret, tree_to_array($child, $fchildrens));        }        unset($node[$fchildrens]);        $ret[] = $node;    } else {        $ret[] = $node;    }    return $ret;}/** * 根据指定的键值对数组排序 * * @param array $array 要排序的数组 * @param string $keyname 键值名称 * @param int $sortDirection 排序方向 * * @return array */function array_column_sort($array, $keyname, $sortDirection = SORT_ASC){    return array_sortby_multifields($array, array($keyname => $sortDirection));}/** * 将一个二维数组按照指定列进行排序,类似 SQL 语句中的 ORDER BY * * @param array $rowset * @param array $args */function array_sortby_multifields($rowset, $args){    $sortArray = array();    $sortRule = '';    foreach ($args as $sortField => $sortDir) {        foreach ($rowset as $offset => $row) {            $sortArray[$sortField][$offset] = $row[$sortField];        }        $sortRule .= '$sortArray[\'' . $sortField . '\'], ' . $sortDir . ', ';    }    if (empty($sortArray) || empty($sortRule)) { return $rowset; }    eval('array_multisort(' . $sortRule . '$rowset);');    return $rowset;}/*description: 交换数组中两个元素的位置,元素包括key和value,具体用法见下面的例子$arr = array (11 => 'a', 22 => 'b', 33 => 'c', 44 => 'd' );$res = array_exchange ( $arr, 11, 33 );*/function array_exchange($arr, $arg1, $arg2) {	$r = range ( 0, count ( $arr ) - 1 );	$res = $res_bak = array_combine ( $r, array_keys ( $arr ) );	$change = array ($arg1, $arg2 );	list ( $res [array_search ( $change [0], $res_bak )], $res [array_search ( $change [1], $res_bak )] ) = array ($change [1], $change [0] );	foreach ( $res as $v ) {		$array [$v] = $arr [$v];	}	return $array;} /*假设:给定一个大数组和一个字符串,要求在这个大数组中查找出比这个字符串大的5个元素。对于一个小数组(如:几十个元素以下的数组),可以采用循环的办法来一个一个进行比较,但是对于大数组来说,这个方法显然是不行,这需要找一个快速查找定位的解决办法。$search = 'arr';$array = array (	'abs',		'acos',	'acosh',	'addcslashes',	'addslashes',	'aggregate_info',	'array_diff',	'array_fill_keys',	'array_fill',	'array_filter',	'base64_encode',	'basename',	'bcadd',	'bccomp',);$arrpos = array_pos($array,$search);   //定位$arr = array_slice($array,$arrpos,5);  //取出数组print_r($arr);快速查找的结果:Array(    [0] => array_diff    [1] => array_fill_keys    [2] => array_fill    [3] => array_filter    [4] => base64_encode)*/function array_pos($array,$search){	if(empty($array)) return false;	if(!$search) return 0;	sort($array);	$array_turn = array_flip($array);	if(isset($array_turn[$search]))	{		$arrpos = $array_turn[$search];	}	else 	{		$tmp_arr = $array;		$tmp_arr[] = $search;		sort($tmp_arr);		$tmp_arr_turn = array_flip($tmp_arr);		$arrpos = $tmp_arr_turn[$search];	}	return $arrpos;}/** * 对数据进行编码转换 * @param array/string $data       数组 * @param string $input     需要转换的编码 * @param string $output    转换后的编码 */function array_iconv($data, $input = 'gbk', $output = 'utf-8') {	if (!is_array($data)) {		return iconv($input, $output, $data);	} else {		foreach ($data as $key=>$val) {			if(is_array($val)) {				$data[$key] = array_iconv($val, $input, $output);			} else {				$data[$key] = iconv($input, $output, $val);			}		}		return $data;	}}/**$str ="array (  'workflowid' => '',  'ishtml' => '0',  'content_ishtml' => '0',  'create_to_html_root' => '0',)";$setting = string2array($str);$setting:Array(    [workflowid] =>     [ishtml] => 0    [content_ishtml] => 0    [create_to_html_root] => 0)**//** * 将字符串转换为数组 * * @param	string	$data	字符串 * @return	array	返回数组格式,如果,data为空,则返回空数组 */function string2array($data) {	if($data == '') return array();	eval("\$array = $data;");	return $array;}/** * 返回经stripslashes处理过的字符串或数组 * @param $string 需要处理的字符串或数组 * @return mixed */function new_stripslashes($string) {	if(!is_array($string)) return stripslashes($string);	foreach($string as $key => $val) $string[$key] = new_stripslashes($val);	return $string;}/*** 将数组转换为字符串** @param	array	$data		数组* @param	bool	$isformdata	如果为0,则不使用new_stripslashes处理,可选参数,默认为1* @return	string	返回字符串,如果,data为空,则返回空*/function array2string($data, $isformdata = 1) {	if($data == '') return '';	if($isformdata) $data = new_stripslashes($data);	return addslashes(var_export($data, TRUE));}/*  * 数组转换成对象$array = array('name' => 'one',               'sex' => 'two',			   'test'=>array('a'=>'ss','dd'),               'old' => 'three'			  );$arrayobject = array2Object($array);echo $arrayobject->name;  // oneprint_r(object2Array($arrayobject));   */function array2Object($array){	if(!is_array($array)) return $array;	$object = new stdClass();	if(is_array($array) && count($array) > 0)	{		foreach($array as $name=>$value)		{			$name = strtolower(trim($name));			if($name) $object->$name = array2Object($value);		}		return $object;	}	else return FALSE;} /*  * 对象转换成数组  */function object2Array($objParam) {	$obj_param = ( array ) $objParam;	foreach ( $obj_param as $key => $value ) {		if (is_object ( $value )) {			object2Array ( $value );			$obj_param [$key] = ( array ) $value;		}	}	return $obj_param;}//数组开头添加元素 保持原始key不变 arrayUnshift($arr, array('test'=>'4'))function arrayUnshift($arrParams, $arrAdd) {	$arr_keys = array ();	$arr_values = array ();	$arr_add_keys = array_keys ( $arrAdd );	$arr_keys = array ($arr_add_keys [0] );	$arr_values = array ($arrAdd [$arr_add_keys [0]] );	foreach ( $arrParams as $key => $value ) {		array_push ( $arr_keys, $key );		array_push ( $arr_values, $value );	}	$arr_result = array_combine ( $arr_keys, $arr_values );	return $arr_result;} //获取多维数组下特定键下的值,并生成一维数组 function getKey2Array(array $arr, $key){	if (!trim($key)) return false;	preg_match_all("/\"$key\";\w{1}:(?:\d+:|)(.*?);/", serialize($arr), $output);	return $output[1];}//多维数组转一维数组 $arr=array('123.html','456.html',array('dw.html','fl.html',array('ps.html','fw.html')),'ab.html');function rebuild_array($arr){  //rebuild a array	static $tmp=array();	for($i=0; $i<count($arr); $i++){		if(is_array($arr[$i])){			rebuild_array($arr[$i]);		}else{			$tmp[]=$arr[$i];		}	}	return $tmp;}
Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools