Home >php教程 >php手册 >删除数组元素实用的PHP数组函数

删除数组元素实用的PHP数组函数

WBOY
WBOYOriginal
2016-06-13 12:27:34986browse

/**
* 从数组中删除空白的元素(包括只有空白字符的元素)
*
* @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;
}
}
}
}







/**
* 将一个二维数组转换为 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;
}

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