• PHP-数组类型


    数组类型

    数组是在程序设计中,为了处理方便, 把若干变量按有序的形式组织起来的一种形式。 按数组键值类型的不同,数组又可分为数值索引数组、字符关联数组。

    基础知识

    • 所谓的数组下标可以视为资料内容在此数组中的识别名称,通常被称为数组下标。
    • 当索引值为数值时,也代表此资料内容在数组中的储存位置。
    • 数组中有几个索引值就被称为几维数组。

    数组分类

    在PHP中有两种数组:索引数组和关联数组。

    • 索引(indexed)数组的索引值是整数,以0开始。当通过位置来标识东西时用索引数组。
    • 关联(associative)数组以字符串做为索引值,关联数组更像操作表。索引值为列名,用于访问列的数据
    $arr 	= [1,2,3] // 索引数组
    $users 	= ['name'=>'向军大叔','age'=>99]; //关联数组
    

    一维数组

    数组值为单个变量(非数组)时,为一维数组

    $arr = ['name'=>'向军','url'=>'houdunren.com'];
    

    多维数组

    数组的值为数组时,这样的数组为多维数组,嵌套几层即几为数组

    $users = [
    	['name'=>'向军'],
    	['name'=>'李四']
    ];
    

    数组赋值

    $arr = [];
    $arr[0] = '后盾人';
    $arr['url']=>'houdunren.com';
    

    读取元素

    key — 从关联数组中取得键名

    $arr = ['后盾人','HDCMS','向军大叔'];
    echo key($arr); //返回0
    

    current — 返回数组中的当前单元

    $arr = ['后盾人','HDCMS','向军大叔'];
    echo current($arr); //返回 '后盾人'
    

    next — 将数组中的内部指针向下移动一位,并返回值。没有更多单元时返回 FALSE

    $arr = ['后盾人','HDCMS','向军大叔'];
    echo next($arr); //返回 'HDCMS'
    

    prev — 将数组的内部指针倒回一位,并返回值。没有更多单元时返回 FALSE

    $arr = ['后盾人','HDCMS','向军大叔'];
    var_dump(prev($arr)); //返回 FALSE
    

    指针遍历

    $users = [
        ['name'=>'向军大叔','age'=>16],
        ['name'=>'小明','age'=>22],
        ['name'=>'李四','age'=>34],
        ['name'=>'张三','age'=>19],
    ];
    ?>
    <table border="1">
    <tr><th>编号</th><th>姓名</th><th>年龄</th></tr>
    <?php while ($user = current($users)):?>
    <tr>
    	<td><?php echo key($users)+1?></td>
    	<td><?php echo $user['name']?></td>
    	<td><?php echo $user['age']?></td>
    </tr>
    <?php  next($users); endwhile;?>
    </table>
    

    遍历数组

    foreach

    $users = [
        ['name'=>'向军大叔','url'=>'aoxiangjun.com'],
        ['name'=>'后盾人','url'=>'houdunren.com']
    ];
    foreach ($users as $key=>$user) {
        echo "[{$key}] 姓名:{$user['name']} 网址:{$user['url']} <hr/>";
    }
    

    list

    把数组中的值赋给一组变量

    $arr = ['向军','hdcms'];
    list($name, $soft) = $arr;
    echo $soft;
    

    直接显示第三个

    $arr = ['向军','hdcms','houdunren.com'];
    list(, , $web) = $arr;
    echo $web;
    

    使用键名

    $users = [
        ['name'=>'向军大叔','age'=>16],
        ['name'=>'小明','age'=>22],
        ['name'=>'李四','age'=>34],
        ['name'=>'张三','age'=>19],
    ];
    while (list('name'=>$name, 'age'=>$age) = current($users)) {
        echo "name: {$name} <hr/>";
        next($users);
    }
    

    常用函数

    下面我们学习常用的数组操作函数,之后你就可以自行参考 官方手册 掌握其他函数了。

    array_push

    将一个或多个单元压入数组的末尾,这是传址操作。

    $users =['向军大叔','小明'];
    array_push($users, '张三');
    print_r($users);
    

    array_pop

    弹出数组最后一个单元(出栈),这是传址操作。

    $users =['向军大叔','小明'];
    array_pop($users);
    print_r($users);
    

    array_shift

    将数组开头的单元移出数组,这是传址操作。

    $users =['向军大叔','小明'];
    array_shift($users);
    print_r($users);
    

    array_unshift

    在数组开头插入一个或多个单元

    $users =['向军大叔','小明'];
    array_unshift($users, '后盾人');
    print_r($users);
    

    count

    count — 计算数组中的单元数目,或对象中的属性个数

    $users = ['向军大叔','小明'];
    echo count($users);
    

    in_array

    检查数组中是否存在某个值

    $allowImageType = ['jpeg','jpg','png'];
    $file = 'hdcms.txt';
    $ext = strtolower(substr(strrchr($file, '.'), 1));
    if (!in_array($ext, $allowImageType)) {
        echo 'is wrong';
    }
    

    array_key_exists

    检查数组里是否有指定的键名或索引

    $allowImageType = ['jpeg'=>2000000,'jpg'=>2000000,'png'=>2000000];
    $file = 'hdcms.txt';
    $ext = strtolower(substr(strrchr($file, '.'), 1));
    if (!array_key_exists($ext, $allowImageType)) {
        echo 'is wrong';
    }
    

    array_keys

    $allowImageType = ['jpeg'=>2000000,'jpg'=>2000000,'png'=>2000000];
    $file = 'hdcms.jpg';
    $ext = strtolower(substr(strrchr($file, '.'), 1));
    if (!in_array($ext, array_keys($allowImageType))) {
        echo 'is wrong';
    }
    

    array_filter

    用回调函数过滤数组中的单元,下面是只获取男生的操作。

    $users = [
        ['name'=>'向军大叔','sex'=>'男','age'=>20],
        ['name'=>'小丽','sex'=>'女','age'=>33]
    ];
    
    print_r(array_filter($users, function ($user) {
        return $user['sex']=='男';
    }));
    

    array_map

    为数组的每个元素应用回调函数,下面是删除用户年龄的操作。

    $users = [
        ['name'=>'向军大叔','sex'=>'男','age'=>20],
        ['name'=>'小丽','sex'=>'女','age'=>33]
    ];
    
    print_r(array_map(function ($user) {
        unset($user['age']);
        return $user;
    }, $users));
    

    获取所有会员名称

    $users = [
        ['name'=>'向军大叔','sex'=>'男','age'=>20],
        ['name'=>'小丽','sex'=>'女','age'=>33]
    ];
    
    print_r(array_map(function ($user) {
        return $user['name'];
    }, $users));
    

    array_values

    返回数组中所有的值

    $formats = array_map(function ($user) {
        return implode('-', array_values($user));
    }, $users);
    print_r($formats); //输出 Array ( [0] => 向军大叔-男-20 [1] => 小丽-女-33 )
    

    array_merge

    合并一个或多个数组

    $database = [
        'host'=>'localhost','port'=>3306,'user'=>'root','password'=>''
    ];
    
    print_r(
        array_merge($database, ['user'=>'hdcms','password'=>'admin888'])
    );
    

    array_change_key_case

    将数组中的所有键名修改为全大写或小写

    //键名转大写
    print_r(array_change_key_case($database, CASE_UPPER));
    
    //键名转小写
    print_r(array_change_key_case($database, CASE_LOWER));
    

    递归改变数组键名

    $config = [
        'database'=>['host'=>'localhost','port'=>3306,'user'=>'root','password'=>''],
        'app'=>['name'=>'向军大叔','url'=>'http://houdunren.com','app'=>["hdcms"]]
    ];
    
    function hd_array_change_key_case(array $data, int $type=CASE_UPPER):array
    {
        foreach ($data as $k=>$v):
            $action = $type ==CASE_UPPER?'strtoupper':'strtolower';
        	unset($data[$k]);
        	$data[$action($k)] = is_array($v)?hd_array_change_key_case($v, $type):$v;
        endforeach;
        return $data;
    }
    print_r(hd_array_change_key_case($config));
    

    递归改变数组值

    $config = [
        'database'=>['host'=>'localhost','port'=>3306,'user'=>'root','password'=>''],
        'app'=>['name'=>'向军大叔','url'=>'http://houdunren.com','app'=>["hdcms"]]
    ];
    
    function hd_array_change_value_case(array $data, int $type=CASE_UPPER):array
    {
        foreach ($data as $k=>$v):
            $action = $type ==CASE_UPPER?'strtoupper':'strtolower';
        $data[$k] = is_array($v)?hd_array_change_value_case($v, $type):$action($v);
        endforeach;
        return $data;
    }
    print_r(hd_array_change_value_case($config));
    

    array_walk_recursive

    对数组中的每个成员递归地应用用户函数,本函数会递归到更深层的数组中去。下面是改变数组键值的操作。

    $config = [
        'database'=>['host'=>'localhost','port'=>3306,'user'=>'root','password'=>''],
        'app'=>['name'=>'向军大叔','url'=>'http://houdunren.com',['app'=>'hdcms']]
    ];
    
    function change_array_value(array $data, int $type=CASE_UPPER):array
    {
        array_walk_recursive($data, function (&$value, $key, $type) {
            $action = $type==CASE_UPPER?'strtoupper':'strtolower';
            $value=$action($value);
        }, $type);
        return $data;
    }
    print_r(change_array_value($config));
    

    var_export

    输出或返回一个变量的字符串表示,第二个参数为 TRUE 时返回字符串。

    $config = [
        'database'=>['host'=>'localhost','port'=>3306,'user'=>'root','password'=>''],
        'app'=>['name'=>'向军大叔','url'=>'http://houdunren.com']
    ];
    
    //生成合法的PHP代码
    $configContent = "<?php return ".var_export($config, true).';';
    file_put_contents('database.php', $configContent);
    

    serialize

    将数组序列化为字符串。

    $config = [
        'database'=>['host'=>'localhost','port'=>3306,'user'=>'root','password'=>''],
        'app'=>['name'=>'向军大叔','url'=>'http://houdunren.com',['app'=>'hdcms']]
    ];
    echo serialize($config);
    

    unserialize

    从已存储的表示中创建 PHP 的值,下面是缓存数据的操作实例。

    $config = [
        'database'=>['host'=>'localhost','port'=>3306,'user'=>'root','password'=>''],
        'app'=>['name'=>'向军大叔','url'=>'http://houdunren.com',['app'=>'hdcms']]
    ];
    
    function cache(string $name, array $data=null)
    {
        $file = 'cache'.DIRECTORY_SEPARATOR.md5($name).'.php';
        if (is_null($data)) {
            $content = is_file($file)?file_get_contents($file):null;
            return unserialize($content)?:null;
        } else {
            return file_put_contents($file, serialize($data));
        }
    }
    
    cache('database', $config);
    var_dump(cache('database'));
    
  • 相关阅读:
    苹果审核被拒,Guideline 1.1.6
    Java基础:类与继承
    Java中的static关键字解析
    Entity Framework 预备知识
    Entity Framework Code First执行SQL语句、视图及存储过程
    java多线程技能
    流与文件
    多线程
    集合
    断言
  • 原文地址:https://www.cnblogs.com/pengcode/p/12585368.html
Copyright © 2020-2023  润新知