1. 程式人生 > >php常用功能函式收集

php常用功能函式收集

1、多維陣列根據某項排序

private function multi_array_sort($multi_array, $sort_key, $sort=SORT_ASC){ 
		if(is_array($multi_array)){ 
			foreach ($multi_array as $row_array){ 
				if(is_array($row_array)){ 
					$key_array[] = $row_array[$sort_key]; 
				} else { 
					return false; 
				} 
			} 
		} else { 
			return false; 
		} 
		array_multisort($key_array,$sort,$multi_array); 
		return $multi_array; 
	} 

來源:http://moper.me/php-multidimensional-array-sort.html

2、多維數組合並

//合併itemsearch的結果
	private function mergeList(&$arr)
	{
		$data = array();
		$n = &$arr;
		foreach ($n as $key => $value) {
			if(!$value) continue;
			array_push($data,$this->getItem($value,$n));
		}
		return array_filter($data);
	}
	private function getItem(&$item,&$arr){
		foreach ($arr as $key => $value) {
			if(!$value) {
				continue;
			};
			if($item["itemTypeName"] == $value["itemTypeName"]
			&& $item["weight"] == $value["weight"]
			&& $item["type"] == $value["type"]){
				if($item["itemTypeId"] == $value["itemTypeId"]
					&& $item["warehouseId"] == $value["warehouseId"]){
					continue;	
				}else{
					$item["stockIn"] += $value["stockIn"];
					$item["remain"] += $value["remain"];
					$item["stockOut"] += $value["stockOut"];
					$item["stockIn"] = sprintf("%.4f",$item["stockIn"]);
					$item["remain"] = sprintf("%.4f",$item["remain"]);
					$item["stockOut"] = sprintf("%.4f",$item["stockOut"]);
					$arr[$key] = "";
				}
			}
		}
		return $item;
	}



3、物件轉換成陣列

function objectToArray($d) {
	if (is_object($d)) {
		// Gets the properties of the given object
		// with get_object_vars function
		$d = get_object_vars($d);
	}

	if (is_array($d)) {
		/*
		* Return array converted to object
		* Using __FUNCTION__ (Magic constant)
		* for recursive call
		*/
		return array_map(__FUNCTION__, $d);
	}
	else {
		// Return array
		return $d;
	}
}



4、 陣列轉換成物件

function arrayToObject($d) {
	if (is_array($d)) {
		/*
		* Return array converted to object
		* Using __FUNCTION__ (Magic constant)
		* for recursive call
		*/
		return (object) array_map(__FUNCTION__, $d);
	}
	else {
		// Return object
		return $d;
	}
}



5、HTML特殊字元轉換

function htmlspecialcharsx($str) {
	$s = htmlspecialchars($str);
	return str_replace('&#', '&#', $s);
}


6、 毫秒格式陣列

function microtime_format() {
    $time = number_format(microtime(true),8,'.','');
	return explode(".", $time);
}