每日学习php记录(二)

248 阅读3分钟

数组

  • 数组就是一组数据,有下标的数据,可遍历。
  • 一维数组是,一个数组里只有一种数据。
  • 二维数组是,一个数组里有一堆数组
$arr = [
    ['name'=>'lin','creted_at'=>'2020-6-18'],
    ['name'=>'er','creted_at'=>'2020-6-28']
];

echo $arr[0];
  • 数组新增值,新增值是不可以不用加上索引值的,他默认会自动自增

    $arr = [0 => '小名'];
    $arr[] = '李四';
    $arr[] = '李五';
    $arr[] = '李六';
    print_r($arr);
    
  • 修改一维数组的某一项值

    $user = [
        'name'=>'关关','age'=>'22'
    ];
    $user['age']='33';
    print_r($user);
    
  • 修改二维数组的某一项值

    $user = [
        ['name'=>'关关','age'=>'22'],
        ['name'=>'花花','age'=>'12']
    ];
    $user[1]['age']='33';
    print_r($user);
    
  • 拿到数组key值和内容的方法

    $arr = [
        'name'=>'a'
    ];
    //拿内容
    echo current($arr);
    
    //拿key值
    echo key($arr);
    
    //往下拿数据,传址的方式,如果没有使用next , current会一直拿
    	//第一个数据	
    next($arr)
        
    //往上取值,和next是对立关系
    prev($arr)
    
  • 数组demo

    $users = [
        ['name'=>'a','age'=>'1'],
        ['name'=>'b','age'=>'2'],
        ['name'=>'c','age'=>'3'],
        ['name'=>'d','age'=>'4']
    ];
    
    
    
    ?>
    
    <table border="1">
        <tr>
            <th>id</th>
            <th>名称</th>
            <th>岁数</th>
        </tr>
        <!-- 获取数据的内容 -->
        <?php while($user = current($users)):?>
        <tr>
            <!-- 因为系统默认从0开始的 -->
            <td><?php echo key($users)+1;?></td>
            <td><?php echo $user['name'];?></td>
            <td><?php echo $user['age'];?></td>
        </tr>
    
        <!-- 这里必须加上next 要不然就会一直渲染第一个数组,不会向下执行 -->
        <?php next($users); endwhile; ?>
    </table>
    
  • list方法操作数组

    $user = ['name'=>'向军','age'=>'33'];
    
    /*
        这里是php7的新增函数
        有点类似js的解构赋值
    */
    list('name'=>$name,'age'=>$abc) = $user;
    
    echo $abc;
    
    • 配合while循环输出数组
    $users = [
        ['name'=>'向军','age'=>'33'],
        ['name'=>'小黄','age'=>'12'],
        ['name'=>'李四','age'=>'44']
    ];
    //配合while循环
    while (list('name'=>$name,'age'=>$age) = current($users)):
        echo "{$name},{$age}<br/>";
        next($users);
    endwhile;
    
    
  • foreach循环来遍历数组

    • 使用foreach循环,可以对数组更多的操作

      foreach ($users as $key => $user) {
          //取他的小标,以及数组里name的数据
          echo ($key+1).'='.$user['name'].'<br/>';
          // print_r($user);
          echo ($users[$key]['age']+=50).'<br/>';
      }
      
  • 数组添加,删除方法

    $users = [
        ['name'=>'向军','age'=>'33'],
        ['name'=>'小黄','age'=>'12'],
        ['name'=>'李四','age'=>'44']
    ];
    
    $min = ['name'=>'阿明','age'=>'22'];
    
    //添加一个元素在原数组后
    array_push($users, $min);
    //添加一个元素在原数组前面
    array_unshift($users,$min);
    
    //删除数组的第一个元素
    array_shift($users);
    //删除数组最后一个元素
    array_pop($users);
    
    echo count($users);
    
    foreach ($users as $key => $value) {
        # code...
        // print_r(next($users));
        echo $users[$key]['name'].'<br/>';
    }
    

尽量使用php内置的数组处理函数,如果没有符合自己要求的,再自己写一个,php自身自带的数组处理函数,效率是很高的

  • 检测数组demo

    $allowImageType = ['jpeg'=>200000,'jpg'=>200000,'png'=>200000];
    $file = 'hdcms.jpg';
    
    //strtolower把字符串转为小写,substr提取字符串中某一项,strrchr查找字符串最后一次出的那项
    $ext = strtolower(substr(strrchr($file,'.'),1));
    //array_key_exists检查数组里是否有指定的键名或索引 --要检查的键   --一个数组,包含带检查的键
    if(!array_key_exists($ext,$allowImageType)){
        echo 'wrong';
    }else {
        echo 'success';
    }
    
  • 判断数组demo

    $allowImageType = ['jpeg','jpg','png'];
    $file = 'hdcms.sss';
    
    //strtolower把字符串转为小写,substr提取字符串中某一项,strrchr查找字符串最后一次出的那项
    $ext = strtolower(substr(strrchr($file,'.'),1));
    
    if (in_array($ext,$allowImageType)) {
        # code...
        echo 'true';
    } else {
        # code...
        echo 'false';
    }
    
  • 筛选数据

    $users = [
        ['name'=>'向军','age'=>'33'],
        ['name'=>'小黄','age'=>'12'],
        ['name'=>'李四','age'=>'44']
    ];
    $filterUsers = array_filter($users, function($user){
        return $user['age']<20;
    });
    print_r($filterUsers);
    
  • implode把一维数组转为字符串,可以加入一个参数,把他们链接成一个自定义的字符串

    $users = [
        ['name'=>'向军','age'=>'33'],
        ['name'=>'小黄','age'=>'12'],
        ['name'=>'李四','age'=>'44']
    ];
    
    $mapUsers = array_map(function(&$user){
        //implode可以将一个一维数组转化为字符串,用glue将一维数组的值链接为一个字符串。
        // print_r(implode('-',array_values($user)));
        print_r(implode('-',$user));
        // unset($user['age']);
        // return $user['name'];
        // $user['class'] = 'abc';
        // return $user;
    },$users);
    
  • array_merge()可以合并数组里面的单元,如果有相同字符串名的则会覆盖前一个,但数字名的不会覆盖而是附加到后面。

    $database = include 'config/database.php';
    
    $database = array_merge($database, ['host'=>'127.0.0.1','possword'=>'admin888']);
    
    print_r($database);
    
  • array_change_key_case把键名改为大小写**CASE_UPPER** 或 CASE_LOWER(默认值)

    $database = include 'config/database.php';
    
    $database = array_change_key_case($database,CASE_UPPER);
    
    // $database = array_change_key_case($database,CASE_LOWER);
    
    print_r($database);
    
    • 利用递归的方式
    $database = include 'config/database.php';
    
    function lin_array_change_key_case(array $data, int $type=CASE_UPPER):array {
        foreach ($data as $key => $value):
            # code...
            $action = $type == CASE_UPPER?'strtoupper':'strtolower';
            //删除旧变量
            unset($data[$key]);
            $data[$action($key)] = is_array($value)?lin_array_change_key_case($value,$type):$value;
        endforeach;
        return $data;
    }
    print_r(lin_array_change_key_case($database, CASE_LOWER));
    
  • 递归操作多维数组

    $database = include 'config/database.php';
    
    function lin_array_change_value_case(array $data, int $case=CASE_UPPER):array{
        $action = $case == CASE_UPPER?'strtoupper':'strtolower';
        foreach ($data as $key => $value) {
            # code...
            $data[$key] = is_array($value)?lin_array_change_value_case($value, $case):$action($value);
        }   
        return  $data;
    }
    print_r(lin_array_change_value_case($database, CASE_UPPER));
    
  • array_walk_recursive() 对数组中的每个成员递归地应用用户函数,将用户自定义函数 callback应用到array数组中的每个单元。本函数会递归到更深层的数组中去

$database = include 'config/database.php';

function array_change_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(array_change_value($database,CASE_UPPER));
  • file_put_contents()方法可用来创建一个文件

    file_put_contents('database.php','<?php return  '.$config.';');
    
    
  • file_put_contents() 将一个字符串写入文件

function cache(string $name, array $data=null){
    //
    $file = 'cache'.DIRECTORY_SEPARATOR.md5($name).'.php';
    if (is_null($data)) {
        # code...
        $content = is_file($file)?file_get_contents($file):null;
        return unserialize($content)?:null;
    } else {
        # code...
        return file_put_contents($file,serialize($data));
    }
}
$config = include "database.php";
// cache('database',$config);

print_r(cache('database'));