1. 统计数组元素个数

$arr = array(
      \'1011,1003,1008,1001,1000,1004,1012\',
      \'1009\',
      \'1011,1003,1111\'
    );
$result = array();
foreach ($arr as $str) {
  $str_arr = explode(\',\', $str);
  foreach ($str_arr as $v) {
    // $result[$v] = isset($result[$v]) ? $result[$v] : 0;
    // $result[$v] = $result[$v] + 1;
    $result[$v] = isset($result[$v]) ? $result[$v]+1 : 1;
  }
}

print_r($result);
//Array
(

[1011] => 2
[1003] => 2
[1008] => 1
[1001] => 1
[1000] => 1
[1004] => 1
[1012] => 1
[1009] => 1
[1111] => 1

)

  1. 循环删除目录

function cleanup_directory($dir) {
  foreach (new DirectoryIterator($dir) as $file) {
    if ($file->isDir()) {
      if (! $file->isDot()) {
        cleanup_directory($file->getPathname());
      }
    } else {
       unlink($file->getPathname());
    }
  }
   rmdir($dir);
}

3.无限极分类生成树


function generateTree($items){

    $tree = array();

    foreach($items as $item){

        if(isset($items[$item[\'pid\']])){

            $items[$item[\'pid\']][\'son\'][] = &$items[$item[\'id\']];

        }else{

            $tree[] = &$items[$item[\'id\']];

        }

    }

    return $tree;

}
function generateTree2($items){

    foreach($items as $item)

        $items[$item[\'pid\']][\'son\'][$item[\'id\']] = &$items[$item[\'id\']];

    return isset($items[0][\'son\']) ? $items[0][\'son\'] : array();

}


$items = array(

    1 => array(\'id\' => 1, \'pid\' => 0, \'name\' => \'安徽省\'),

    2 => array(\'id\' => 2, \'pid\' => 0, \'name\' => \'浙江省\'),

    3 => array(\'id\' => 3, \'pid\' => 1, \'name\' => \'合肥市\'),

    4 => array(\'id\' => 4, \'pid\' => 3, \'name\' => \'长丰县\'),

    5 => array(\'id\' => 5, \'pid\' => 1, \'name\' => \'安庆市\'),

);

print_r(generateTree($items));
/**

 * 如何取数据格式化的树形数据

 */

$tree = generateTree($items);

function getTreeData($tree){

    foreach($tree as $t){

        echo $t[\'name\'].\'
\'; if(isset($t[\'son\'])){ getTreeData($t[\'son\']); } } }

4.数组排序 a – b 是数字数组写法 遇到字符串的时候就要

var test = [\'ab\', \'ac\', \'bd\', \'bc\'];
test.sort(function(a, b) {
    if(a < b) {
        return -1;
    }

    if(a > b) {
        return 1;
    }

    return 0;
});

5.array_reduce

$raw = [1,2,3,4,5,];
// array_reduce 的第三个参数是 $result 的初始值
array_reduce($raw, function($result, $value) {
    $result[$value] = $value;

    return $result;
}, []);
// [1 => 1, 2 => 2, ... 5 => 5]

6.arraymap 闭包中只接受一个或者多个参数,闭包的参数数量和 arraymap 本身的参数数量必须一致

$input = [\'key\' => \'value\'];
array_map(function($key, $value) {

    echo $key . $value;
}, array_keys($input), $input)
// \'keyvalue\'
$double = function($item) {
  return 2 * $item;
}

$result = array_map($double, [1,2,3]);

// 2 4 6

7.繁殖兔子

$month = 12;
   $fab = array();
 
   $fab[0] = 1;
   $fab[1] = 1;
 
     for ($i = 2; $i < $month; $i++)
     {
         $fab[$i] = $fab[$i - 1] + $fab[$i - 2];
     }
 
     for ($i = 0; $i < $month; $i++)
     {
         echo sprintf(\"第{%d}个月兔子为:{%d}\",$i, $fab[$i]).\"
\"; }

8 .datetime

function getCurMonthFirstDay($date)
{
    return date(\'Y-m-01\', strtotime($date));
}
 getCurMonthLastDay(\'2015-07-23\')
function getCurMonthLastDay($date)
{
    return date(\'Y-m-d\', strtotime(date(\'Y-m-01\', strtotime($date)) . \' +1 month -1 day\'));
}

9.加密解密

function encrypt($data, $key)

{

    $key    =   md5($key);

    $x      =   0;

    $len    =   strlen($data);

    $l      =   strlen($key);

    $char   =   \'\';

    for ($i = 0; $i < $len; $i++)

    {

        if ($x == $l)

        {

            $x = 0;

        }

        $char .= $key{$x};

        $x++;

    }

    $str    =   \'\';

    for ($i = 0; $i < $len; $i++)

    {

        $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);

    }

    return base64_encode($str);

}

 

function decrypt($data, $key)

{

    $key = md5($key);

    $x = 0;

    $data = base64_decode($data);

    $len = strlen($data);

    $l = strlen($key);

    $char = \'\';

    for ($i = 0; $i < $len; $i++)

    {

        if ($x == $l)

        {

            $x = 0;

        }

        $char .= substr($key, $x, 1);

        $x++;

    }

    $str = \'\';

    for ($i = 0; $i < $len; $i++)

    {

        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1)))

        {

            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));

        }

        else

        {

            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));

        }

    }

    return $str;

}

10 . 多维数组降级

function array_flatten($arr) {
    $result = [];

    array_walk_recursive($arr, function($value) use (&$result) {
        $result[] = $value;
    });

    return $result;
}
print_r(array_flatten([1,[2,3],[4,5]]));// [1,[2,3],[4,5]] => [1,2,3,4,5]
//  var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
var test = [1,2,3,[4,5,6],[7,8]];
[].concat.apply([], test); // [1,2,3,4,5,6,7,8] 对于 test 数组中的每一个 value, 将它 concat 到空数组 [] 中去,而因为 concat 是 Array 的 prototype,所以我们用一个空 array 作载体
var test1 = [1,2,[3,[4,[5]]]];

function flatten(arr) {
   return arr.reduce(function(pre, cur) {
        if(Array.isArray(cur)) {
            return flatten(pre.concat(cur));
        }

        return pre.concat(cur);
   }, []);
}

// [1,2,3,4,5]

11.json_encode中文


function json_encode_wrapper ($result)
{
    if(defined(\'JSON_UNESCAPED_UNICODE\')){
        return json_encode($result,JSON_UNESCAPED_UNICODE|JSON_NUMERIC_CHECK);
    }else {
        return preg_replace(
            array(\"#\\\\\\u([0-9a-f][0-9a-f][0-9a-f][0-9a-f])#ie\", \"/\\\"(\\d+)\\\"/\",),
            array(\"iconv(\'UCS-2\', \'UTF-8\', pack(\'H4\', \'\\\\1\'))\", \"\\\\1\"),
            json_encode($result)
        );
    }
}

12.二维数组去重

$arr = array(

    array(\'id\'=>\'2\',\'title\'=>\'...\',\'ding\'=>\'1\',\'jing\'=>\'1\',\'time\'=>\'...\',\'url\'=>\'...\',\'dj\'=>\'...\'),

    array(\'id\'=>\'2\',\'title\'=>\'...\',\'ding\'=>\'1\',\'jing\'=>\'1\',\'time\'=>\'...\',\'url\'=>\'...\',\'dj\'=>\'...\')

);
function about_unique($arr=array()){  
   /*将该种二维数组看成一维数组,则      该一维数组的value值有相同的则干掉只留一个,并将该一维      数组用重排后的索引数组返回,而返回的一维数组中的每个元素都是      原始key值形成的关联数组    */    
$keys =array();
   $temp = array();
   foreach($arr[0] as $k=>$arrays) {
    /*数组记录下关联数组的key值*/     
    $keys[] = $k;
   }
   //return $keys;    /*降维*/    
foreach($arr as $k=>$v) {
    $v = join(\",\",$v);  //降维     
    $temp[] = $v;
   }
   $temp = array_unique($temp); //去掉重复的内容    
foreach ($temp as $k => $v){
    /*再将拆开的数组按索引数组重新组装*/     
    $temp[$k] = explode(\",\",$v);  
   } 
   //return $temp;    /*再将拆开的数组按关联数组key值重新组装*/    
foreach($temp as $k=>$v) {
    foreach($v as $kkk=>$ck) {
     $data[$k][$keys[$kkk]] = $temp[$k][$kkk];
    }
   }
   return $data;
  }

13.格式化字节大小

/**
* 格式化字节大小
* @param  number $size      字节数
* @param  string $delimiter 数字和单位分隔符
* @return string            格式化后的带单位的大小
* @author 
*/
function format_bytes($size, $delimiter = \'\') {
  $units = array(\'B\', \'KB\', \'MB\', \'GB\', \'TB\', \'PB\');
  for ($i = 0; $size >= 1024 && $i < 6; $i++) $size /= 1024;
  return round($size, 2) . $delimiter . $units[$i];
}

14.3分钟前

/**
* 将指定时间戳转换为截止当前的xx时间前的格式  例如 return \'3分钟前\'\'
* @param string|int $timestamp unix时间戳
* @return string
*/
function time_ago($timestamp) {
    $etime = time() - $timestamp;
    if ($etime < 1) return \'刚刚\';     
    $interval = array (         
      12 * 30 * 24 * 60 * 60  =>  \'年前 (\'.date(\'Y-m-d\', $timestamp).\')\',
      30 * 24 * 60 * 60       =>  \'个月前 (\'.date(\'m-d\', $timestamp).\')\',
      7 * 24 * 60 * 60        =>  \'周前 (\'.date(\'m-d\', $timestamp).\')\',
      24 * 60 * 60            =>  \'天前\',
      60 * 60                 =>  \'小时前\',
      60                      =>  \'分钟前\',
      1                       =>  \'秒前\'
    );
    foreach ($interval as $secs => $str) {
        $d = $etime / $secs;
        if ($d >= 1) {
            $r = round($d);
            return $r . $str;
        }
    };
}

15.身份证号

/**
* 判断参数字符串是否为天朝身份证号
* @param $id 需要被判断的字符串或数字
* @return mixed false 或 array[有内容的array boolean为真]
*/
function is_citizen_id($id) {
    //长度效验  18位身份证中的X为大写
    $id  = strtoupper($id);
    if(!(preg_match(\'/^\\d{17}(\\d|X)$/\',$id) || preg_match(\'/^\\d{15}$/\',$id))) {
      return false;
    }
    //15位老号码转换为18位 并转换成字符串
    $Wi          = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1); 
    $Ai          = array(\'1\', \'0\', \'X\', \'9\', \'8\', \'7\', \'6\', \'5\', \'4\', \'3\', \'2\'); 
    $cardNoSum   = 0;
    if(strlen($id)==16) {
        $id        = substr(0, 6).\'19\'.substr(6, 9); 
        for($i = 0; $i < 17; $i++) {
          $cardNoSum += substr($id,$i,1) * $Wi[$i];
        }  
        $seq       = $cardNoSum % 11; 
        $id        = $id.$Ai[$seq];
    }
    //效验18位身份证最后一位字符的合法性
    $cardNoSum   = 0;
    $id17        = substr($id,0,17);
    $lastString  = substr($id,17,1);
    for($i = 0; $i < 17; $i++) {
        $cardNoSum += substr($id,$i,1) * $Wi[$i];
    }  
    $seq         = $cardNoSum % 11;
    $realString  = $Ai[$seq];
    if($lastString!=$realString) {return false;}
    //地域效验
    $oCity       =  array(11=>\"北京\",12=>\"天津\",13=>\"河北\",14=>\"山西\",15=>\"内蒙古\",21=>\"辽宁\",22=>\"吉林\",23=>\"黑龙江\",31=>\"上海\",32=>\"江苏\",33=>\"浙江\",34=>\"安徽\",35=>\"福建\",36=>\"江西\",37=>\"山东\",41=>\"河南\",42=>\"湖北\",43=>\"湖南\",44=>\"广东\",45=>\"广西\",46=>\"海南\",50=>\"重庆\",51=>\"四川\",52=>\"贵州\",53=>\"云南\",54=>\"西藏\",61=>\"陕西\",62=>\"甘肃\",63=>\"青海\",64=>\"宁夏\",65=>\"新疆\",71=>\"台湾\",81=>\"香港\",82=>\"澳门\",91=>\"国外\");
    $City        = substr($id, 0, 2);
    $BirthYear   = substr($id, 6, 4);
    $BirthMonth  = substr($id, 10, 2);
    $BirthDay    = substr($id, 12, 2);
    $Sex         = substr($id, 16,1) % 2 ;//男1 女0
    //$Sexcn       = $Sex?\'男\':\'女\';
    //地域验证
    if(is_null($oCity[$City])) {return false;}
    //出生日期效验
    if($BirthYear>2078 || $BirthYear<1900) {return false;}
    $RealDate    = strtotime($BirthYear.\'-\'.$BirthMonth.\'-\'.$BirthDay);
    if(date(\'Y\',$RealDate)!=$BirthYear || date(\'m\',$RealDate)!=$BirthMonth || date(\'d\',$RealDate)!=$BirthDay) {
        return false;
    }
    return array(\'id\'=>$id,\'location\'=>$oCity[$City],\'Y\'=>$BirthYear,\'m\'=>$BirthMonth,\'d\'=>$BirthDay,\'sex\'=>$Sex);
}

16.获取二维数组中某个key的集合

$user = array( 0 => array( \'id\' => 1, \'name\' => \'张三\', \'email\' => \'zhangsan@sina.com\', ), 1 => array( \'id\' => 2, \'name\' => \'李四\', \'email\' => \'lisi@163.com\', ), 2 => array( \'id\' => 5, \'name\' => \'王五\', \'email\' => \'10000@qq.com\', ), ...... );
$ids = array(); $ids = array_map(\'array_shift\', $user);
$ids = array_column($user, \'id\');//php5.5
$names = array(); $names = array_reduce($user, create_function(\'$v,$w\', \'$v[$w[\"id\"]]=$w[\"name\"];return $v;\'));

17.判断一个数是否为素数

function isPrime(number) {

   // If your browser doesn\'t support the method Number.isInteger of ECMAScript 6,
   // you can implement your own pretty easily
   if (typeof number !== \'number\' || !Number.isInteger(number)) {
      // Alternatively you can throw an error.
      return false;
   }
 
   if (number < 2) {
      return false;
   }
    
   if (number === 2) {
      return true;
   } else if (number % 2 === 0) {
      return false;
   }
 
   var squareRoot = Math.sqrt(number);
   for(var i = 3; i <= squareRoot; i += 2) {
      if (number % i === 0) {
         return false;
      }
   }
 
   return true;
}
function isPrime($n) {//TurkHackTeam AVP production
    if ($n <= 3) {
        return $n > 1;
    } else if ($n % 2 === 0 || $n % 3 === 0) {
        return false;
    } else {
        for ($i = 5; $i * $i <= $n; $i += 6) {
            if ($n % $i === 0 || $n % ($i + 2) === 0) {
                return false;
            }
        }
        return true;
    }
}

18.闭包

var nodes = document.getElementsByTagName(\'button\');
for (var i = 0; i < nodes.length; i++) {
   nodes[i].addEventListener(\'click\', (function(i) {
      return function() {
         console.log(\'You clicked element #\' + i);
      }
   })(i));
}
//将函数移动到循环外部即可(创建了一个新的闭包对象)
function handlerWrapper(i) {
   return function() {
      console.log(\'You clicked element #\' + i);
   }
}
 
var nodes = document.getElementsByTagName(\'button\');
for (var i = 0; i < nodes.length; i++) {
   nodes[i].addEventListener(\'click\', handlerWrapper(i));
}

19.事件循环 Event Loop

function printing() {
   console.log(1); 
   setTimeout(function() { console.log(2); }, 1000); 
   setTimeout(function() { console.log(3); }, 0); 
   console.log(4);
}
 //即使setTimeout的延迟为0,其回调也会被加入到那些没有延迟的函数队列之后。
printing();//1432

20.字典排序

def mysort():
    dic = {\'a\':31, \'bc\':5, \'c\':3, \'asd\':4, \'aa\':74, \'d\':0}
    dict= sorted(dic.iteritems(), key=lambda d:d[1], reverse = True)
    print dict//[(\'aa\', 74), (\'a\', 31), (\'bc\', 5), (\'asd\', 4), (\'c\', 3), (\'d\', 0)]

21.数值缩写

var abbr = function (number) {
    var abbrList = [\'\', \'K\', \'M\', \'G\', \'T\', \'P\', \'E\', \'Z\', \'Y\'];
    var step = 1000;
    var i = 0;
    var j = abbrList.length;

    while (number >= step && ++i < j) {
        number = number / step;
    }

    if (i === j) {
        i = j - 1;
    }
    

    return number + abbrList[i];
};

22.数字千位分隔符

var format = function (number) {
    return String(number).replace(/(\\d)(?=(\\d{3})+$)/g, \'$1,\');
};

23.实现随机颜色值

var randomColor = function () {
    var letters = \'0123456789ABCDEF\';
    var ret = \'#\';

    for (var i = 0; i < 6; i++) {
        ret += letters[Math.round(Math.random() * 15)];
    }

    return ret;
};
var randomColor = function () {
    return \'#\' + Math.random().toString(16).substr(2, 6);
};

24.时间格式化输出

//formatDate(new Date(1409894060000), \'yyyy-MM-dd HH:mm:ss 星期w\') 2014-09-05 13:14:20 星期五
function formatDate(oDate, sFormation) {
    var obj = {
        yyyy:oDate.getFullYear(),
        yy:(\"\"+ oDate.getFullYear()).slice(-2),//非常精辟的方法
        M:oDate.getMonth()+1,
        MM:(\"0\"+ (oDate.getMonth()+1)).slice(-2),
        d:oDate.getDate(),
        dd:(\"0\" + oDate.getDate()).slice(-2),
        H:oDate.getHours(),
        HH:(\"0\" + oDate.getHours()).slice(-2),
        h:oDate.getHours() % 12,
        hh:(\"0\"+oDate.getHours() % 12).slice(-2),
        m:oDate.getMinutes(),
        mm:(\"0\" + oDate.getMinutes()).slice(-2),
        s:oDate.getSeconds(),
        ss:(\"0\" + oDate.getSeconds()).slice(-2),
        w:[\'日\', \'一\', \'二\', \'三\', \'四\', \'五\', \'六\'][oDate.getDay()]
    };
    return sFormation.replace(/([a-z]+)/ig,function($1){return obj[$1]});
}

25.斐波那契数列

function fibonacci(n) {
    if(n ==1 || n == 2){
        return 1
    }
    return fibonacci(n - 1) + fibonacci(n - 2);
}

26.数组去重


Array.prototype.distinct=function(){
    var arr=[];
    var obj={};
    for(var i=0;i

27.删除元素

function array_delete($array, $element) {
    return array_diff($array, [$element]);
   // if(($key = array_search($array, $element)) !== false) {
      //  unset($array[$key]);
   // }
//$array = array_filter($array, function($e) use ($del_val) {
 //   return ($e !== $del_val);
//});
//$array = array(14,22,37,42,58,61,73,82,96,10);
//array_splice($array, array_search(58, $array ), 1);
}

array_delete( [312, 401, 1599, 3], 401 ) // returns [312, 1599, 3]

28.RandomString

def random_string(length):
    return \'\'.join(random.choice(string.letters + string.digits) for i in xrange(length))


function generateRandomString($length = 10) {
    $characters = \'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\';
    $charactersLength = strlen($characters);
    $randomString = \'\';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
//$randomString = substr(str_shuffle(\"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"), 0, $length);
//$string = bin2hex(openssl_random_pseudo_bytes(10));20 char long hexdec string

29.保存文件

$ch = curl_init(\'http://example.com/image.php\');
$fp = fopen(\'/my/folder/flower.gif\', \'wb\');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

30.插入数组元素

function array_insert(&$array, $position, $insert)
{
    if (is_int($position)) {
        array_splice($array, $position, 0, $insert);
    } else {
        $pos   = array_search($position, array_keys($array));
        $array = array_merge(
            array_slice($array, 0, $pos),
            $insert,
            array_slice($array, $pos)
        );
    }
}
$arr = [
    \"name\"  => [
        \"type\"      => \"string\",
        \"maxlength\" => \"30\",
    ],
    \"email\" => [
        \"type\"      => \"email\",
        \"maxlength\" => \"150\",
    ],
];

array_insert(
    $arr,
    \"email\",
    [
        \"phone\" => [
            \"type\"   => \"string\",
            \"format\" => \"phone\",
        ],
    ]
);
// ->
array (
  \'name\' =>
  array (
    \'type\' => \'string\',
    \'maxlength\' => \'30\',
  ),
  \'phone\' =>
  array (
    \'type\' => \'string\',
    \'format\' => \'phone\',
  ),
  \'email\' =>
  array (
    \'type\' => \'email\',
    \'maxlength\' => \'150\',
  ),
)

31.验证ip


function validate_ip($ip)
    {
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE) === false)
            return false;
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) === false)
            return false;
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false && filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false)
            return false;

        return true;
    }
    function validate_ip($ip)
{
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false)
    {
        return false;
    }

    self::$ip = sprintf(\'%u\', ip2long($ip)); // you seem to want this

    return true;
}

32.get ip

function get_ip_address(){
    foreach (array(\'HTTP_CLIENT_IP\', \'HTTP_X_FORWARDED_FOR\', \'HTTP_X_FORWARDED\', \'HTTP_X_CLUSTER_CLIENT_IP\', \'HTTP_FORWARDED_FOR\', \'HTTP_FORWARDED\', \'REMOTE_ADDR\') as $key){
        if (array_key_exists($key, $_SERVER) === true){
            foreach (explode(\',\', $_SERVER[$key]) as $ip){
                $ip = trim($ip); // just to be safe

                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false){
                    return $ip;
                }
            }
        }
    }
}

33.选出最长的单词

function LongestWord(sen) {
    var words = sen.match(/\\w+/g);
    if (words !== null) {
        var maxWords = {
            index: 0,
            length: 0
        };
        for (var i = 0, length = words.length; i < length; i++) {
            if (words[i].length > maxWords.length) {
                maxWords = {
                    index: i,
                    length: words[i].length
                }
            }
        }
        return words[maxWords.index];
    }
    return words;
}

34.map

var oldArr = [{first_name:\"Colin\",last_name:\"Toh\"},{first_name:\"Addy\",last_name:\"Osmani\"},{first_name:\"Yehuda\",last_name:\"Katz\"}];

function getNewArr(){
        
    return oldArr.map(function(item,index){
        item.full_name = [item.first_name,item.last_name].join(\" \");
        return item;
    });
    
}

35.统计一个数组中有多少个不重复的单词

var arr = [\"apple\",\"orange\",\"apple\",\"orange\",\"pear\",\"orange\"];
//https://github.com/es-shims/es5-shim
function getWordCnt(){
    var obj = {};
    
    for(var i= 0, l = arr.length; i< l; i++){
        var item = arr[i];
        obj[item] = (obj[item] +1 ) || 1;//obj[item]为undefined则返回1
    }
    
    return obj;
}
function getWordCnt(){
    return arr.reduce(function(prev,next){
        prev[next] = (prev[next] + 1) || 1;
        return prev;
    },{});
}

36.约瑟夫环

function yuesefu($n,$m) {  
    $r=0;  
    for($i=2; $i<=$n; $i++) {
        $r=($r+$m)%$i;  
    }
    return $r+1;  
}  
echo yuesefu(10,3).\"是猴王\";

37.判断一个字符串中的字符是否都在另一个中出现

function charsissubset($h, $n) {
    return preg_match(\'/[^\' . preg_quote($h) . \']/u\', $n) ? 0 : 1;
}

echo charsissubset(\'abcddcba\', \'abcde\'); // false
echo charsissubset(\'abcddcba\', \'abcd\'); // true
echo charsissubset(\'abcddcba\', \'badc\'); // true
echo charsissubset(\'汉字\', \'字\'); // true
echo charsissubset(\'汉字\', \'漢字\'); // false

38.add(2)(3)(4)

function add(a) {
  var temp = function(b) {
    return add(a + b);
  }
  temp.valueOf = temp.toString = function() {
    return a;
  };
  return temp;
}
var ans = add(2)(3)(4);//9
function add(num){
  num += ~~add;
  add.num = num;
  return add;
}
add.valueOf = add.toString = function(){return add.num};
var ans = add(3)(4)(5)(6);  // 18

39.打印出Fibonacci数

function fn(n) {
  var a = [];
  a[0] = 0, a[1] = 1;
  for(var i = 2; i < n; i++)
    a[i] = a[i - 1] + a[i - 2];
  for(var i = 0; i < n; i++)
    console.log(a[i]);
}

40.把URL参数解析为一个对象

function parseQueryString(url) {
  var obj = {};
  var a = url.split(\'?\');
  if(a.length === 1) return obj;
  var b = a[1].split(\'&\');
  for(var i = 0, length = b.length; i < length; i++) {
    var c = b[i].split(\'=\');
    obj[c[0]] = c[1];
  }
  return obj;
}
var url = \'http://witmax.cn/index.php?key0=0&key1=1&key2=2\';
var obj = parseQueryString(url);
console.log(obj.key0, obj.key1, obj.key2);  // 0 1 2 

41.判断数据类型

function isNumber(obj) {
    return Object.prototype.toString.call(obj) === \'[object Number]\'
}//对于NaN也返回true
function isNumber(obj) {
    return obj === +obj
}
// 判断字符串
function isString(obj) {
    return obj === obj+\'\'
}
// 判断布尔类型
function isBoolean(obj) {
    return obj === !!obj
}

42.javascript sleep

function sleep(numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
        now = new Date();
        if (now.getTime() > exitTime)
        return;
    }
}

43.爬虫

def splider():
    # -*- coding:utf-8 -*-
    #发送data表单数据
    import urllib2
    import urllib
    url = \"http://www.someserver.com/register.cgi\"
    values = {
        \'name\' : \'Andrew\',
        \'location\' : \'NJU\',
        \'language\' : \'Python\'
    }
    user_agent = \'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)\' 
    header = {\'User-Agent\' : user_agent}
    data = urllib.urlencode(values) #data数据需要编码成标准形式
    #print data
    http_handler = urllib2.HTTPHandler(debuglevel = 1)#Debug log
    https_handler = urllib2.HTTPSHandler(debuglevel = 1)
    opener = urllib2.build_opener(http_handler, https_handler)
    urllib2.install_opener(opener)
    req = urllib2.Request(url, data) #发送请求同时传送data表单
    #req = urllib2.Request(url, data, header) #url 表单数据 伪装头部
    reponse = urllib2.urlopen(req, timeout=10) #接受反馈数据
    html = reponse.read() #读取反馈数据
    print response.info()
    print response.getcode()
    redirected = response.geturl() == url
    \"\"\"
    full_url = url + \'?\' + data
    data = urllib2.open(full_url)
    \"\"\"
    #返回错误码, 200不是错误, 不会引起异常
    headers = {
    \'Referer\': \'http://www.cnbeta.com/articles\'
    }
    proxy_handler = urllib2.ProxyHandler({\"http\" : \'http://some-proxy.com:8080\'})
    opener = urllib2.build_opener(proxy_handler)
    urllib2.install_opener(opener)  #urllib2.install_opener() 会设置 urllib2 的全局 opener
    req = urllib2.Request(
    url = \'http://secure.verycd.com/signin/*/http://www.verycd.com/\',
    data = post_data, 
    headers = headers
    )
    try:
        urllib2.urlopen(req)
    except urllib2.HTTPError, e:
        print e.code
        #print e.read()

44.判断数据类型

function type(o) {
    var t, c, n;
    if (o === null) 
        return \"null\";
    if (o !== o)
        return \"nan\";
    if ((t = typeof o) !== \"object\") 
        return t;  // 识别原始值的类型和函数
    if ((c = classof(o)) !== \"Object\")
        return c;  // 识别出大多数内置类型
    if (o.constructor && typeof o.constructor === \"function\" &&
        (n = o.constructor.getName()))
        return n;  //如果对象构造函数名字存在, 则返回
    return \"Object\";  // 无法识别类型返回\"Object\"
}
function classof(o) {
    return Object.prototype.toString.call(o).slice(8, -1);
}
Function.prototype.getName = function() {
    if (\"name\" in this)
        return this.name;
    return this.name = this.toString().match(/function\\s*([^(]*)\\(/)[1];
}

45.实现千分位分隔

function mysplit(s){
        if(/[^0-9\\.]/.test(s)) return \"invalid value\";
        s=s.replace(/^(\\d*)$/,\"$1.\");
        s=(s+\"00\").replace(/(\\d*\\.\\d\\d)\\d*/,\"$1\");
        s=s.replace(\".\",\",\");
        var re=/(\\d)(\\d{3},)/;
        while(re.test(s))
            s=s.replace(re,\"$1,$2\");
        s=s.replace(/,(\\d\\d)$/,\".$1\");
        return \"¥\" + s.replace(/^\\./,\"0.\")
    }

46.随机产生颜色

function randomVal(val){
        return Math.floor(Math.random()*(val + 1));
    }

    function randomColor(){
        return \'rgb(\' + randomVal(255) + \',\' + randomVal(255) + \',\' + randomVal(255) + \')\';
    }

47.生成随机的IP地址,规则类似于192.168.11.0/24

RANDOM_IP_POOL=[\'192.168.10.222/0\']
def __get_random_ip():
    str_ip = RANDOM_IP_POOL[random.randint(0,len(RANDOM_IP_POOL) - 1)]
    str_ip_addr = str_ip.split(\'/\')[0]
    str_ip_mask = str_ip.split(\'/\')[1]
    ip_addr = struct.unpack(\'>I\',socket.inet_aton(str_ip_addr))[0]
    mask = 0x0
    for i in range(31, 31 - int(str_ip_mask), -1):
        mask = mask | ( 1 << i)
    ip_addr_min = ip_addr & (mask & 0xffffffff)
    ip_addr_max = ip_addr | (~mask & 0xffffffff)
    return socket.inet_ntoa(struct.pack(\'>I\', random.randint(ip_addr_min, ip_addr_max)))

48.倒计时

var total = 500;
var timer = null;

var tiktock = document.getElementById(\'tiktock\');
var btn = document.getElementById(\'btn\');

function countdown(){
    timer = setInterval(function(){
        total--;
        if (total<=0) {
            clearInterval(timer);
            tiktock.innerHTML= \"0:00\";
        }else{
            var ss = Math.floor(total/100);
            var ms = total-Math.floor(total/100)*100;
            tiktock.innerHTML=ss + \":\" + ms;
        }
    },10);
};
btn.addEventListener(\'click\', countdown, false);

49.[1,2,3] ->\'{1,2,3}\’

class intSet(object):

def __init__(self):
    # creat an empty set of integers
    self.vals = []

def insert(self, e):
    # assume e is an interger, and insert it 
    if not(e in self.vals):
        self.vals.append(e)

def member(self, e):
    return e in self.vals

def remove(self, e):
    try:
        self.vals.remove(e)
    except:
        raise ValueError(str(e) + \'not found\')


def __str__(self):
    # return a string representation of self
    self.vals.sort()
    return \"{\" + \',\'.join([str(e) for e in self.vals]) + \"}\"

50.转义过滤

//纯数字的参数intval强制取整
//其他参数值进行过滤或者转义
//filter_input() 函数来过滤一个 POST 变量
if (!filter_input(INPUT_POST, \'email\', FILTER_VALIDATE_EMAIL))
 {
 echo \"E-Mail is not valid\";
 }
else
 {
 echo \"E-Mail is valid\";
 }
    protected function zaddslashes($string, $force = 0, $strip = FALSE)
    {   
        if (!defined(\'MAGIC_QUOTES_GPC\'))
        {   
         define(\'MAGIC_QUOTES_GPC\', \'\');
        }   
        if (!MAGIC_QUOTES_GPC || $force)
        {   
         if (is_array($string)) {
             foreach ($string as $key => $val)
             {   
                 $string[$key] = $this->zaddslashes($val, $force, $strip);
             }   
         }   
         else
         {   
             $string = ($strip ? stripslashes($string) : $string);
             $string = htmlspecialchars($string);
         }   
        }   
        return $string;
     }

51.构造IP

function getIPaddress()
{
    $IPaddress = \'\';
    if (isset($_SERVER)) {
        if (isset($_SERVER[\"HTTP_X_FORWARDED_FOR\"])) {
            $IPaddress = $_SERVER[\"HTTP_X_FORWARDED_FOR\"];
        } else if (isset($_SERVER[\"HTTP_CLIENT_IP\"])) {
            $IPaddress = $_SERVER[\"HTTP_CLIENT_IP\"];
        } else {
            $IPaddress = $_SERVER[\"REMOTE_ADDR\"];
        }
    } else {
        if (getenv(\"HTTP_X_FORWARDED_FOR\")) {
            $IPaddress = getenv(\"HTTP_X_FORWARDED_FOR\");
        } else if (getenv(\"HTTP_CLIENT_IP\")) {
            $IPaddress = getenv(\"HTTP_CLIENT_IP\");
        } else {
            $IPaddress = getenv(\"REMOTE_ADDR\");
        }
    }
    return $IPaddress;
}
function curlPost($url, $post=\'\', $autoFollow=0){
        $ch = curl_init();
        $user_agent = \'Safari Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.73.11 (KHTML, like Gecko) Version/7.0.1 Safari/5
        curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
        
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
        curl_setopt($ch, CURLOPT_HEADER, 0); 
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(\'X-FORWARDED-FOR:61.135.169.125\', \'CLIENT-IP:\'.getIPaddress()));  //构造IP
        curl_setopt($ch, CURLOPT_REFERER, \"http://www.baidu.com/\");   //构造来路
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, \'GET\');
        if($autoFollow){
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);  //启动跳转链接
            curl_setopt($ch, CURLOPT_AUTOREFERER, true);  //多级自动跳转
        }   
        //  
        if($post!=\'\'){
            curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }   
        
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

52.文件名生成唯一

function unique_filename() {
    $time = !empty($_SERVER[\'REQUEST_TIME_FLOAT\']) ? $_SERVER[\'REQUEST_TIME_FLOAT\'] : mt_rand();
    $addr = !empty($_SERVER[\'REMOTE_ADDR\'])        ? $_SERVER[\'REMOTE_ADDR\']        : mt_rand();
    $port = !empty($_SERVER[\'REMOTE_PORT\'])        ? $_SERVER[\'REMOTE_PORT\']        : mt_rand();
    $ua   = !empty($_SERVER[\'HTTP_USER_AGENT\'])    ? $_SERVER[\'HTTP_USER_AGENT\']    : mt_rand();
    return md5(uniqid(mt_rand(), true).$time.$addr.$port.$ua.mt_rand());
}

53.PHP实现钩子和插件系统

/**
 * Attach (or remove) multiple callbacks to an event and trigger those callbacks when that event is called.
 * 绑定或移除多个回调函数到事件,当事件被调用时触发回调函数.
 *
 * @param string $event name
 * @param mixed  $value the optional value to pass to each callback
 * @param mixed  $callback the method or function to call - FALSE to remove all callbacks for event
 */
function event($event, $value = NULL, $callback = NULL) {
    static $events;
    if($callback !== NULL) {
        if($callback) {
            $events[$event][] = $callback; // 添加事件
        } else {
            unset($events[$event]); // 移除事件里所有的回调函数
        }
    } else if(isset($events[$event])) {
        foreach($events[$event] as $function) {
            $value = call_user_func($function, $value); // 调用事件
        }
        return $value;
    }
}
// 添加事件
event(\'filter_text\', NULL, function($text) { return htmlspecialchars($text); });
event(\'filter_text\', NULL, function($text) { return nl2br($text); });
// 移除事件里所有的回调函数
// event(\'filter_text\', NULL, FALSE);
// 调用事件
$text = event(\'filter_text\', $_POST[\'text\']);

54.字符串首字母大写的实现方式

String.prototype.firstUpperCase = function(){
    return this.replace(/\\b(\\w)(\\w*)/g, function($0, $1, $2) {
        return $1.toUpperCase() + $2.toLowerCase();
    });
}
//这只能改变字符串首字母
String.prototype.firstUpperCase=function(){
    return this.replace(/^\\S/,function(s){return s.toUpperCase();});
}

55.获取url参数

 function getQueryString(key){
        var reg = new RegExp(\"(^|&)\"+key+\"=([^&]*)(&|$)\");
        var result = window.location.search.substr(1).match(reg);
        return result?decodeURIComponent(result[2]):null;
      }
function getRequest() {   
       var url = window.location.search; //获取url中\"?\"符后的字串   
       var theRequest = new Object();   
       if (url.indexOf(\"?\") != -1) {   
          var str = url.substr(1);   
          strs = str.split(\"&\");   
          for(var i = 0; i < strs.length; i ++) {   
             theRequest[strs[i].split(\"=\")[0]]=decodeURI(strs[i].split(\"=\")[1]); 

          }   
       }   
       return theRequest;   
    }

56.过滤

var array = [
    {
        \"title\": 123,
        \"num\": 1,
        \"type\": [{\"name\": \'A\', \"num\": 1}, {\"name\": \'B\', \"num\": 1}, {\"name\": \'C\', \"num\": 0}]
    }, {
        \"title\": 321,
        \"num\": 1,
        \"type\": [{\"name\": \'D\', \"num\": 0}, {\"name\": \'E\', \"num\": 1}, {\"name\": \'F\', \"num\": 0}]
    }];

array.forEach(function (x) {
    x.type = x.type.filter(function (y) {
        return y.num != 0;
    });
});

57.随机生成-50到50之间的不包括0的整数

function my_rand(){
    $num = mt_rand(1, 50); 
    $rand = mt_rand(1, 10);

    return $rand > 4 ? $num : -$num;//控制生成正负数的比例为4:6
}

58.时间对比

function compareDate(date1, date2){
      var  difArr, unitArr;

      date1 = new Date(date1);
      date2 = new Date(date2);
      difArr = [date1.getFullYear() - date2.getFullYear(), date1.getMonth() -date2.getMonth(),date1.getDate() - date2.getDate(),date1.getHours() - date2.getHours(), date1.getMinutes() - date2.getMinutes(),date1.getSeconds() - date2.getSeconds()];
      unitArr = [\'年\',\'月\',\'日\',\'时\',\'分\',\'秒\']
      for(var i = 0; i < 6;i++){
        if(difArr[i] !== 0){
          return Math.abs(difArr[i]) + unitArr[i];
        }
      }
    }

59.数组去重

//传入数组
  function unique(arr){
    var tmpArr = [];
    for(var i=0; i

60.继承

/*
 * 基类,定义属性
 */
function Person(name, age) {
    this.name = name;
    this.age = age;
}

/*
 * 基类,定义方法
 */
Person.prototype.selfIntroduce = function () {
    console.log(\"name: \" + this.name);
    console.log(\"age: \" + this.age);
}

/*
 * 子类,定义子类的属性
 */
function Student(name, age, school) {
  // 调用基类的构造函数
    Person.call(this, name, age);
    this.school = school;
}

// 使子类继承基类
Student.prototype = new Person();

/*
 * 定义子类的方法
 */
Student.prototype.goToSchool = function() {
  // some code..
}

/*
 * 扩展并调用了超类的方法
 */
Student.prototype.selfIntroduce = function () {
    Student.prototype.__proto__.selfIntroduce.call(this);
    console.log(\"school: \" + this.school);
}

var student = new Student(\"John\", 22, \"My School\");
student.selfIntroduce();

61.Unicode和Utf-8编码的互相转换

/**
 * utf8字符转换成Unicode字符
 * @param  [type] $utf8_str Utf-8字符
 * @return [type]           Unicode字符
 */
function utf8_str_to_unicode($utf8_str) {
    $unicode = 0;
    $unicode = (ord($utf8_str[0]) & 0x1F) << 12;
    $unicode |= (ord($utf8_str[1]) & 0x3F) << 6;
    $unicode |= (ord($utf8_str[2]) & 0x3F);
    return dechex($unicode);
}

/**
 * Unicode字符转换成utf8字符
 * @param  [type] $unicode_str Unicode字符
 * @return [type]              Utf-8字符
 */
function unicode_to_utf8($unicode_str) {
    $utf8_str = \'\';
    $code = intval(hexdec($unicode_str));
    //这里注意转换出来的code一定得是整形,这样才会正确的按位操作
    $ord_1 = decbin(0xe0 | ($code >> 12));
    $ord_2 = decbin(0x80 | (($code >> 6) & 0x3f));
    $ord_3 = decbin(0x80 | ($code & 0x3f));
    $utf8_str = chr(bindec($ord_1)) . chr(bindec($ord_2)) . chr(bindec($ord_3));
    return $utf8_str;
}

62.gzip编码

function curl_get($url, $gzip=false){
 $curl = curl_init($url);
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
 if($gzip) curl_setopt($curl, CURLOPT_ENCODING, \"gzip\"); // 关键在这里
 $content = curl_exec($curl);
 curl_close($curl);
 return $content;
}
$url = \'http://api.stackexchange.com/2.2/tags?order=asc&sort=popular&site=stackoverflow&tag=qt\';
//$data = file_get_contents(\"compress.zlib://\".$url);

63.Python中文时间

#!/usr/bin/env 
# -*- coding: utf-8 -*-

from datetime import datetime
nt=datetime.now()
print(nt.strftime(\'%Y年%m月%d日 %H时%M分%S秒\').decode(\'utf-8\'))#2015年08月10日 11时25分04秒
print(nt.strftime(\'%Y{y}%m{m}%d{d}\').format(y=\'年\', m=\'月\', d=\'日\'))

64.list分组,按照下标顺序分成3组:[3, 8, 9] [4, 1, 10] [6, 7, 2, 5]

a=[1,2,3,4,5,6,7,8,9,10]
[a[i:i+3] for i in xrange(0,len(a),3)]

64.curl上传文件

$ch = curl_init();

$data = array(\'name\' => \'Foo\', \'file\' => \'@/home/vagrant/test.png\');

curl_setopt($ch, CURLOPT_URL, \'http://localhost/test/curl/load_file.php\');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);    // 5.6 给改成 true了, 弄回去 
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);

65.IP地址转换为整数型

$ipArr  = explode(\'.\',$_SERVER[\'REMOTE_ADDR\']);
$ip     = $ipArr[0] * 0x1000000
        + $ipArr[1] * 0x10000
        + $ipArr[2] * 0x100
        + $ipArr[3];
        //数字型的IP转为字符型:
$ipVal = $row[\'client_IP\'];
$ipArr = array(
        0 => floor(  $ipVal / 0x1000000) );
$ipVint   = $ipVal-($ipArr[0]*0x1000000); // for clarity
$ipArr[1] = ($ipVint & 0xFF0000)  >> 16;
$ipArr[2] = ($ipVint & 0xFF00  )  >> 8;
$ipArr[3] =  $ipVint & 0xFF;
$ipDotted = implode(\'.\', $ipArr);

66.保存base64图片

$base64_url = \'data:image/jpeg;base64,xxxxxxxxxxxxxxxxxxxxxx\';
$base64_body = substr(strstr($base64_url,\',\'),1);
$data= base64_decode($base64_body );

//存储or创建图片:

file_put_contents($file_path,$data);

或$image = imagecreatefromstring($data);
 $size  =  getimagesizefromstring ( $data);var_dump($size);

//读取图片文件,转换成base64编码格式
$image_file = \'test.jpg\';
$image_info = getimagesize($image_file);
$base64_image_content = \"data:{$image_info[\'mime\']};base64,\" . chunk_split(base64_encode(file_get_contents($image_file)));
 
//保存base64字符串为图片
//匹配出图片的格式
if (preg_match(\'/^(data:\\s*image\\/(\\w+);base64,)/\', $base64_image_content, $result)){
  $type = $result[2];
  $new_file = \"./test.{$type}\";
  if (file_put_contents($new_file, base64_decode(str_replace($result[1], \'\', $base64_image_content)))){
    echo \'新文件保存成功:\', $new_file;
  }
 
}
?>
 
\" />

67.日志记录print_r( $value, true )

/**

错误日志类
*/
class C_Log
{
/**

日志保存目录

@var string
*/
private $path = \'\';
/**

只能运行一个实例

@var [type]
*/
private static $instance;
/**

构造函数

初始化日志文件地址
*/
function __construct($path)
{
$this->path = $path;
}

public function logPrint($name,$value)
{

   //获取时间
   $_o = date(\'Y-m-d H:m:s\',time()).\"\\r\\n\";
   $_o .= \"==\".  $name . \"==\";
   //打印内容
   if( is_array( $value ) || is_object( $value ) ){
       $_o .= print_r( $value, true ). \"\\r\\n\";
     } else {
         $_o .= $value. \"\\r\\n\";
     }
     //输出到文件
     $this->_log($_o);
}
/**fdf

打印日志

@return [type] [description]
*/
private function _log($log){
error_log($log,3,$this->path);
}
/**

输出日志

@return [type] [description]
*/
public static function log($name, $value)
{
if (empty(self::$instance)) {

   self::$instance = new C_Log(__DIR__.\"/error_log.log\");
}
self::$instance->logPrint($name, $value);
}
}

68.过滤子类

function getByClass(parent, classname) {
    var tags = parent.getElementsByTagName(\'*\');
    return [].filter.call(tags, function(t) {
        return t.classList.contains(classname);
    });
}
//

function getByClass(parent, classname) {
    return parent.querySelectorAll(\".\" + classname);
}

69.JSON.stringify

function setProp(obj) {
    for (var p in obj) {
        switch (typeof (obj[p])) {
            case \'object\':
                setProp(obj[p]);
                break;
            case \'undefined\':
                obj[p] = \'\';
                break;
        }
    }
    return obj;
}

JSON.stringify(setProp({ a: 1, b: 2, c: undefined }));//{\"a\":1,\"b\":2,\"c\":\"\"}

70.判断用户的IP是否局域网IP

function is_local_ip($ip_addr = null) {
    if (is_null($ip_addr)) {
        $ip_addr = $_SERVER[\'REMOTE_ADDR\'];
    }
    $ip = ip2long($ip_addr);
    return $ip & 0xffff0000 == 0xc0a80000 // 192.168.0.0/16
        || $ip & 0xfff00000 == 0xac100000 // 172.16.0.0/12
        || $ip & 0xff000000 == 0xa0000000 // 10.0.0.0/8
        || $ip & 0xff000000 == 0x7f000000 // 127.0.0.0/8
    ;
}

71.遍历出当月的所有日子和星期

var d = new Date();         // 这是当天
d.setDate(1);               // 这就是1号
var weekday = d.getDay();   // 1号星期几,从星期天为0开始

d.setMonth(d.getMonth() + 1);
d.setDate(0);               // 这两句得到最当月最后一天
var end = d.getDate();      // 最后一天的日,比如8月就是31

var days = [];
for (var i = 0; i < end; i++) {
    days[i] = {
        day: i + 1,
        week: (weekday + i) % 7
    }
}


console.log(days);

72.Downloading Data From localStorage

var myData = {
    \'a\': \'a\',
    \'b\': \'b\',
    \'c\': \'c\'
};
// add it to our localstorage
localStorage.setItem(\'data\', JSON.stringify(myData));

// encode the data into base64
base64 = window.btoa(localStorage.getItem(\'data\'));

// create an a tag
var a = document.createElement(\'a\');
a.href = \'data:application/octet-stream;base64,\' + base64;
a.innerHTML = \'Download\';

// add to the body
document.body.appendChild(a);

73.\”数据类型\”判断函数

function datatypeof(arg){
    return Object.prototype.toString.call(arg).match(/\\[object\\s(\\w+)\\]/)[1];
}

74.二维数组去除重复,重复值相加

$arr = array(
    array(\'id\' => 123, \'name\' => \'张三\', \'amount\'=>\'1\'),
    array(\'id\' => 123, \'name\' => \'李四\', \'amount\' => \'1\'),
    array(\'id\' => 124, \'name\' => \'王五\', \'amount\' => \'1\'),
    array(\'id\' => 125, \'name\' => \'赵六\', \'amount\' => \'1\'),
    array(\'id\' => 126, \'name\' => \'赵六\', \'amount\' => \'2\'),
    array(\'id\' => 126, \'name\' => \'赵六\', \'amount\' => \'2\')
);

$new = array();

foreach($arr as $row){
    if(isset($new[$row[\'name\']])){
        $new[$row[\'name\']][\'amount\'] += $row[\'amount\'];
    }else{
        $new[$row[\'name\']] = $row;
    }
}

75.含有从属关系的元素重新排列

$arr = array(
    array(\'id\'=>21, \'pid\'=>0, \'name\'=>\'aaa\'),
    array(\'id\'=>22, \'pid\'=>0, \'name\'=>\'bbb\'),
    array(\'id\'=>23, \'pid\'=>0, \'name\'=>\'ccc\'),
    array(\'id\'=>24, \'pid\'=>23, \'name\'=>\'ddd\'),
    array(\'id\'=>25, \'pid\'=>23, \'name\'=>\'eee\'),
    array(\'id\'=>26, \'pid\'=>22, \'name\'=>\'fff\'),
    );

$temp=[];
foreach ($arr as $item)
{
    list($id,$pid,$name) = array_values($item); // 取出数组的值并分别生成变量

    if(array_key_exists($pid, $temp)) 
    // 检查临时数组$temp中是否存在键名与$pid的值相同的键
    {
        $temp[$pid][\'child\'][]=array(\'id\'=>$id,\'pid\'=>$pid,\'name\'=>$name);
        // 如果存在则新增数组至临时数组中键名为 $pid 的子元素 child 内
    }else
        $temp[$id]=array(\'id\'=>$id,\'pid\'=>$pid,\'name\'=>$name);
        // 如果不存在则新增数组至临时数组中并设定键名为 $id
}

$array = array_values($temp);
// 将临时数组中以 $id 为键名的键修改为数字索引

echo \"
\";
print_r($array);
//or 
foreach ($arr as $item)
{
    if (array_key_exists($item[\'pid\'], $temp))
    {       
        $temp[$item[\'pid\']][\'child\'][]=$item;
    }else
        $temp[$item[\'id\']]=$item;
}

76.随机中文字符

//正则表达式匹配中文[\\u4e00-\\u9fa5]
//parseInt(\"4E00\",16) 19968 parseInt(\"9FA5\",16);20901
var randomHz=function(){
    eval( \"var word=\" +  \'\"\\\\u\' + (Math.round(Math.random() * 20901) + 19968).toString(16)+\'\"\');
    return word;
}
for(i=0;i<100;i++){
    console.log(randomHz());
}

77.jQuery解析url

$(document).ready(function () {
    var url = \'http://iwjw.com/codes/code-repository?id=12#top\';
    var a = $(\'\', { href: url});
    var sResult = \'Protocol: \' + a.prop(\'protocol\') + \'
\' + \'Host name: \' + a.prop(\'hostname\') + \'
\' + \'Path: \' + a.prop(\'pathname\') + \'
\' + \'Query: \' + a.prop(\'search\') + \'
\' + \'Hash: \' + a.prop(\'hash\'); $(\'span\').html(sResult); });

78.用JS实现一个数组合并的方法(要求去重)

var arr1 = [\'a\'];
var arr2 = [\'b\', \'c\'];
var arr3 = [\'c\', [\'d\'], \'e\', undefined, null];

var concat = (function(){
  // concat arr1 and arr2 without duplication.
  var concat_ = function(arr1, arr2) {
    for (var i=arr2.length-1;i>=0;i--) {
      arr1.indexOf(arr2[i]) === -1 ? arr1.push(arr2[i]) : 0;
    }
  };
  // concat arbitrary arrays.
  // Instead of alter supplied arrays, return a new one.
  return function(arr) {
    var result = arr.slice();
    for (var i=arguments.length-1;i>=1;i--) {
      concat_(result, arguments[i]);
    }
    return result;
  };
}());
执行:concat(arr1, arr2, arr3)
返回:[ \'a\', null, undefined, \'e\', [ \'d\' ], \'c\', \'b\' ]
var merge = function() {
    return Array.prototype.concat.apply([], arguments)
  }

merge([1,2,4],[3,4],[5,6]);
//[1, 2, 4, 3, 4, 5, 6]

79.字节转化

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());
function cacheMem($key)
{
    static $mem = null;
    if ($mem === null) {
        $mem = new Memcache();
        $mem->connect(\'127.0.0.1\', 11211);
    }

    $data = $mem->get($key);
    if (empty($data)) {
        $data = date(\'Y-m-d H:i:s\');
        $mem->set($key, $data);
    }

    return $data;
}