zoukankan      html  css  js  c++  java
  • 【PHP】巧用PHP数据函数

    整理自微信公众号:https://mp.weixin.qq.com/s/vpPLtYmat4Eiymn4ajGUmA

     

    一、对于某些关联数组,有时候我们只想取指定键名的那部分,比如数组为 ['id' => 1, 'name' => 'zane', 'password' => '123456'] 此时若只想取包含 id 和 name 的部分:

    function newOnlyKeys($array, $keys) {
        return array_intersect_key($array, array_flip($keys));
    }
    $raw = ['id' => 1, 'name' => 'zane', 'password' => '123456'];
    var_dump(newOnlyKeys($raw, ['id', 'name']));  // ['id' => 1, 'name' => 'zane']
    

    解释:

    array_flip:将数组的键和值对调,使数组 ['id', 'name'] 转变为了 ['id' => 0, 'name' => 1]。

    array_intersect_key :使用键名比较计算数组的交集,也就是返回第一个参数数组中与其他参数数组相同键名的值。

     

    二、移除指定键值

    raw = ['id' => 1, 'name' => 'zane', 'password' => '123456'];
    
    function removeKeys($array, $keys) {
        return array_diff_key($array, array_flip($keys));
    }
    
    // 移除 id 键
    var_dump(removeKeys($raw, ['id', 'password'])); //  ['name' => 'zane']
    

      

    三、确认数组中的的值全部为 true

    $power = ['read' => true, 'write' => true, 'execute' => true];
    var_dump((bool)array_product($power)); // 结果 true
    
    
    $power = ['read' => true, 'write' => true, 'execute' => false];
    var_dump((bool)array_product($power)); // 结果 false
    

    解释:

    array_product 函数本来的功能是「计算数组中所有值的乘积」,在累乘数组中所有成员的时候会将成员的值转为数值类型。

    当传递的参数为一个 bool 成员所组成的数组时,众所周知 true 会被转为 1,false 会被转为 0。然后只要数组中出现一个 false 累乘的结果自然会变成 0,然后我们再将结果转为 bool 类型不就是 false 了

     

    注意:

    使用 array_product 函数将在计算过程中将数组成员转为数值类型进行计算,所以请确保你了解数组成员转为数值类型后的值,否则会产生意料之外的结果。比如:

    $power = ['read' => true, 'write' => true, 'execute' => 'true'];
    var_dump((bool)array_product($power)); // 结果 false
    

    上例是因为 'true' 在计算过程中被转为 0。

     

    四、数组中重复次数最多的值

    $data = [6, 11, 11, 2, 4, 4, 11, 6, 7, 4, 2, 11, 8];
    $cv = array_count_values($data); // $cv = [6 => 2, 11 => 4, 2 => 2, 4 => 3, 7 => 1, 8 => 1]
    
    arsort($cv);
    $max = key($cv);
    var_dump($max); // 结果 1
    

      

    得意时做事,失意时读书
  • 相关阅读:
    Android笔记之开机自启
    Android笔记之广播
    Hive笔记之collect_list/collect_set(列转行)
    Hive笔记之数据库操作
    hive笔记之row_number、rank、dense_rank
    Linux Shell管道调用用户定义函数(使shell支持map函数式特性)
    Linux shell爬虫实现树洞网鼓励师(自动回复Robot)
    分享一些免费的接码平台(国外号码)
    爬虫技能之内容提取:如何从有不可见元素混淆的页面中抽取数据
    ctf writeup之程序员密码
  • 原文地址:https://www.cnblogs.com/lanse1993/p/12850384.html
Copyright © 2011-2022 走看看