分享一段代码,实现php中二维数组的排序。
代码:
<?php /** * 二维数组排序 * by www. */ $good = array(); for($i = 0; $i<7 ; $i++ ){ $good[$i]['price'] = rand(1,10000); $good[$i]['hot'] = rand(1,100); $good[$i]['follow'] = rand(1,1000); } echo '<pre>'; print_r($good); echo '</pre>'; $hot=array(); $follow=array(); foreach($good as $k=>$v){ $hot[$k] = $v['hot']; $follow[$k] = $v['follow']; } //二维数组排序 //方法一,先按hot字段降序 ,再按follow降序 array_multisort($hot,SORT_DESC,$follow,SORT_DESC,$good); echo '<pre>'; print_r($good); echo '</pre>'; //方法二 function xx($a, $b) { if ($a['price'] == $b['price']) { return ($a['hot'] < $b['hot']) ? 1 : -1; ; } return ($a['price'] < $b['price']) ? 1 : -1; } $a = array( 0=>array('price'=>123,'hot'=>34543), 1=>array('price'=>434,'hot'=>234), 2=>array('price'=>42,'hot'=>2232), 3=>array('price'=>42,'hot'=>235432), 4=>array('price'=>33443,'hot'=>12), 4=>array('price'=>434,'hot'=>1211), ); usort($a, 'xx'); echo '<pre>'; print_r($a); echo '</pre>';
本节分享一个php cookie类,实现的功能包括:
设置cookie名称、cookie值、过期时间、cookie保存路径、设置cookie所属的域、是否加密,是否仅仅http cookie等。
代码:
<?php
/**
--- CREATE COOKIE OBJECT ---
$c = new cookie();
--- CREATE/UPDATE COOKIE ---
$c->setName('myCookie') // REQUIRED
->setValue($value,true) // REQUIRED - 1st param = data string/array, 2nd param = encrypt (true=yes)
->setExpire('+1 hour') // optional - defaults to "0" or browser close
->setPath('/') // optional - defaults to /
->setDomain('.domain.com') // optional - will try to auto-detect
->setSecure(false) // optional - default false
->setHTTPOnly(false); // optional - default false
$c->createCookie(); // you could chain this too, must be last
--- DESTROY COOKIE ---
$c->setName('myCookie')->destroyCookie();
OR
$c->destroyCookie('myCookie');
--- GET COOKIE ---
$cookie = $c->getCookie('myCookie',true); // 1st param = cookie name, 2nd param = whether to decrypt
// if the value is an array, you'll need to unserialize the return
*/
Class Cookie {
// cookie加密键值串,可以根据自己的需要修改
const DES_KEY = 'o89L7234kjW2Wad72SHw22lPZmEbP3dSj7TT10A5Sh60';
private $errors = array();
private $cookieName = null;
private $cookieData = null;
private $cookieKey = null;
private $cookieExpire = 0;
private $cookiePath = '/';
private $cookieDomain = null;
private $cookieSecure = false;
private $cookieHTTPOnly = false;
/**
* 构造函数 设置域
* @access public
* @return none
*/
public function __construct()
{
$this->cookieDomain = $this->getRootDomain();
}
/**
* 获取cookie值
* @access public
* @param string $cookieName cookie to be retrieved
* @param bool $decrypt whether to decrypt the values
*/
public function getCookie($cookieName=null, $decrypt=false)
{
if(is_null($cookieName)){
$cookieName = $this->cookieName;
}
if(isset($_COOKIE[$cookieName])){
return ($decrypt?$this->cookieEncryption($_COOKIE[$cookieName],true):base64_decode($_COOKIE[$cookieName]));
} else {
$this->pushError($cookieName.' not found');
return false;
}
}
/**
* 创建cookie
* @access public
* @return bool true/false
*/
public function createCookie()
{
if(is_null($this->cookieName)){
$this->pushError('Cookie name was null');
return false;
}
$ret = setcookie(
$this->cookieName,
$this->cookieData,
$this->cookieExpire,
$this->cookiePath,
$this->cookieDomain,
$this->cookieSecure,
$this->cookieHTTPOnly
);
return $ret;
}
/**
* 清除cookie
* @access public
* @param string $cookieName to kill
* @return bool true/false
*/
public function destroyCookie($cookieName=null)
{
if(is_null($cookieName)){
$cookieName = $this->cookieName;
}
$ret = setcookie(
$cookieName,
null,
(time()-1),
$this->cookiePath,
$this->cookieDomain
);
return $ret;
}
/**
* 设置cookie名称
* @access public
* @param string $name cookie name
* @return mixed obj or bool false
*/
public function setName($name=null)
{
if(!is_null($name)){
$this->cookieName = $name;
return $this;
}
$this->pushError('Cookie name was null');
return false;
}
/**
* 设置cookie值
* @access public
* @param string $value cookie value
* @return bool whether the string was a string
*/
public function setValue($value=null, $encrypt=false)
{
if(!is_null($value)){
if(is_array($value)){
$value = serialize($value);
}
$data = ($encrypt?$this->cookieEncryption($value):base64_encode($value));
$len = (function_exists('mb_strlen')?mb_strlen($data):strlen($data));
if($len>4096){
$this->pushError('Cookie data exceeds 4kb');
return false;
}
$this->cookieData = $data;
unset($data);
return $this;
}
$this->pushError('Cookie value was empty');
return false;
}
/**
* 设置cookie的过期时间
* @access public
* @param string $time +1 week, etc.
* @return bool whether the string was a string
*/
public function setExpire($time=0)
{
$pre = substr($time,0,1);
if(in_array($pre, array('+','-'))){
$this->cookieExpire = strtotime($time);
return $this;
} else {
$this->cookieExpire = 0;
return $this;
}
}
/**
* 设置cookie的保存路径
* @access public
* @param string $path
* @return object $this
*/
public function setPath($path='/')
{
$this->cookiePath = $path;
return $this;
}
/**
* 设置cookie所属的域
* @access public
* @param string $domain
* @return object $this
*/
public function setDomain($domain=null)
{
if(!is_null($domain)){
$this->cookieDomain = $domain;
}
return $this;
}
/**
*
* @access public
* @param bool $secure true/false
* @return object $this
*/
public function setSecure($secure=false)
{
$this->cookieSecure = (bool)$secure;
return $this;
}
/**
* HTTPOnly flag, not yet fully supported by all browsers
* @access public
* @param bool $httponly yes/no
* @return object $this
*/
public function setHTTPOnly($httponly=false)
{
$this->cookieHTTPOnly = (bool)$httponly;
return $this;
}
/**
* Jenky bit to retrieve root domain if not supplied
* @access private
* @return string Le Domain
*/
private function getRootDomain()
{
$host = $_SERVER['HTTP_HOST'];
$parts = explode('.', $host);
if(count($parts)>1){
$tld = array_pop($parts);
$domain = array_pop($parts).'.'.$tld;
} else {
$domain = array_pop($parts);
}
return '.'.$domain;
}
/**
* Value Encryption
* @access private
* @param string $str string to be (de|en)crypted
* @param string $decrypt whether to decrypt or not
* @return string (de|en)crypted string
*/
private function cookieEncryption($str=null, $decrypt=false)
{
if(is_null($str)){
$this->pushError('Cannot encrypt/decrypt null string');
return $str;
}
$iv_size = mcrypt_get_iv_size(MCRYPT_3DES, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$key_size = mcrypt_get_key_size(MCRYPT_3DES, MCRYPT_MODE_ECB);
$key = substr(self::DES_KEY,0,$key_size);
if($decrypt){
$return = mcrypt_decrypt(MCRYPT_3DES, $key, base64_decode($str), MCRYPT_MODE_ECB, $iv);
} else {
$return = base64_encode(mcrypt_encrypt(MCRYPT_3DES, $key, $str, MCRYPT_MODE_ECB, $iv));
}
return $return;
}
/**
* Add error to errors array
* @access public
* @param string $error
* @return none
*/
private function pushError($error=null)
{
if(!is_null($error)){
$this->errors[] = $error;
}
return;
}
/**
* Retrieve errors
* @access public
* @return string errors
*/
public function getErrors()
{
return implode("<br />", $this->errors);
}
}
调用示例:
<?php
require('cookie.class.php');
// Sample data
$array = array('foo'=>'bar','bar'=>'foo');
$string = 'this is a string';
$c = new Cookie();
/*
创建一个加密的cookie数组
*/
echo '<h3>Encrypted array</h3>';
$start = microtime(true);
$c->setName('Example') // our cookie name
->setValue($array,true) // second parameter, true, encrypts data
->setExpire('+1 hours') // expires in 1 hour
->setPath('/') // cookie path
->setDomain('localhost') // set for localhost
->createCookie();
$cookie = $c->getCookie('Example',true);
$cookie = unserialize($cookie);
$bench = sprintf('%.8f',(microtime(true)-$start));
echo print_r($cookie,true).'<br />'.$bench.' seconds<hr />';
/*
销毁cookie
*/
//$c->destroyCookie('Example');
/*
创建一个cookie字符串,直接浏览器关闭时失效
*/
echo '<h3>Regular unencrypted string</h3>';
$start = microtime(true);
$c->setName('Example1')
->setValue($string) // Second param could be set to false here
->setExpire(0)
->setPath('/')
->setDomain('localhost')
->createCookie();
$cookie = $c->getCookie('Example1');
$bench = sprintf('%.8f',(microtime(true)-$start));
echo print_r($cookie,true).'<br />'.$bench.' seconds';
在php编程中,尤其是数据库的操盘中,内存消耗有时会很厉害。
可以使用memory_get_usage()函数可获取当前的内存消耗情况。
一,函数原型
int memory_get_usage ([ bool $real_usage = false ] )
二,版本兼容
PHP 4 >= 4.3.2, PHP 5
三,基础用法与实例
1,获取当前的内存消耗量
echo memory_get_usage();
$var = str_repeat("phpzixue.cn", 10000);
echo memory_get_usage();
unset($var);
echo memory_get_usage();
?>
输出:62328 122504 62416
说明:memory_get_usage()函数输出的数值为bytes单位
2,格式化memory_get_usage()输出
function convert($size){
$unit=array('b','kb','mb','gb','tb','pb');
return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
}
echo convert(memory_get_usage(true));
?>
输出:256 kb
3,自定义函数获取数组或变量值大小
function array_size($arr) {
ob_start();
print_r($arr);
$mem = ob_get_contents();
ob_end_clean();
$mem = preg_replace("/\n +/", "", $mem);
$mem = strlen($mem);
return $mem;
}
$memEstimate = array_size($GLOBALS);
?>
说明:
要减少内存的占用,可以使用 PHP unset() 函数把不再需要使用的变量删除。
类似函数:PHP mysql_free_result() 函数,可以清空不再需要的查询数据库得到的结果集,这样也能得到更多可用内存。
PHP memory_get_usage()还可以有个参数,$real_usage,其值为布尔值。默认为 FALSE,表示得到的内存使用量不包括该函数(PHP 内存管理器)占用的内存;
当设置为 TRUE 时,得到的内存为包括该函数(PHP 内存管理器)占用的内存。
在php编程中,可以使用PHP memory_get_usage()比较各个方法占用内存的高低,然后选择性能较好的方法。