• Welcome to Journal web site.

我是 PHP 程序员

- 开发无止境 -

Next
Prev

第5章 0422-常用数组实例演示

Data: 2021-08-20 21:06:15Form: JournalClick: 0

问题集合:

1.  php写函数可以用胖箭头吗?

答:可以的,但有版本限制 , 并且 php中的箭头函数的使用场景非常有限, 特别是内部$this, 捉摸不定, 不像js那样成熟, 建议不要用, 别给自己找事

2.  伙计们,$acc后面的第一个(,)逗号是连接符嘛,为啥不用(.)点那?

image.png

答:一样的,都是连接符

3.  回调 就是  在另一个函数 像传参一样再调一次 叫回调吗

答:大家想多了, 回调通常与事件绑定, 可以主动调用,也可以被动调用

就是函数的一种形式, 不必过度解读

本质上是与字符串,数组一样的数据类型, 只不过存放的是可执行代码, 可以加括号执行罢了




demo1:再谈数组遍历

<?php
// 再谈数组遍历
// ! 1. 指针遍历
$stu = ['id' => 1, 'name' => 'Jack', 'course' => 'php', 'score' => 90];
echo "返回当前指针与数值<br>";
echo "key(), current()<br>";
printf('[%s]=>%s<br>', key($stu), current($stu));
echo "后移<br>";
next($stu);
printf('[%s]=>%s<br>', key($stu), current($stu));
next($stu);
printf('[%s]=>%s<br>', key($stu), current($stu));
next($stu);
printf('[%s]=>%s<br>', key($stu), current($stu));
echo "前移<br>";
prev($stu);
printf('[%s]=>%s<br>', key($stu), current($stu));
echo "复位, 第一个<br>";
reset($stu);
printf('[%s]=>%s<br>', key($stu), current($stu));
echo "最后<br>";
end($stu);
printf('[%s]=>%s<br>', key($stu), current($stu));

echo "2. 自动遍历<br>";
//$stu = [];
//重置指针
reset($stu);
if (count($stu) > 0) {
    while (true) {
        printf('[%s]=>%s<br>', key($stu), current($stu));
        if (next($stu)) continue;
        else break;
    }
} else {
    echo '空数组<br>';
}

echo "3. 快捷遍历<br>";
foreach ($stu as $key => $value) {
    printf('[%s]=>%s<br>', $key, $value);
}
// foreach 还能遍历对象

// ! 4. 解构遍历
// 索引数组
list($id,  $name) = [10, 'Tony'];
// list 不是函数,因为函数不能放在等号左边, 不能用在&ldquo;左值&rdquo;
printf('$id = %s, $name = %s<br>', $id, $name);

// 关联数组
list('id' => $id, 'name' => $name) = ['id' => 10, 'name' => 'Tony'];
printf('$id = %s, $name = %s<br>', $id, $name);
echo '<hr>';

// 解构通常用来遍历二维或以上的数组
$users = [
    ['id' => 10, 'name' => 'Tony'],
    ['id' => 11, 'name' => 'John'],
    ['id' => 12, 'name' => 'Jerry'],
];
// foreach
foreach ($users as list('id' => $id, 'name' => $name)) {
    // print_r($user);
    // printf('$id = %s, $name = %s<br>', $user['id'], $user['name']);
    printf('$id = %s, $name = %s<br>', $id, $name);
}
demo2:数组函数
<?php
// 数组函数
// ! 1. 与值相关
$arr = [3 => 10, 9 => 20, 0 => 'html', 'id' => 'css', 20 => 20, 30];
printf('<pre>%s</pre>', print_r($arr, true));
echo "array_values<br>";
printf('<pre>%s</pre>', print_r(array_values($arr), true));
echo "in_array<br>";
var_dump(in_array('html', $arr));
echo '<hr>';

echo "array_search<br>";
$key = array_search('20', $arr);
echo $arr[$key] . '<br>';

echo "array_unique: 去重<br>";
printf(
    '<pre>%s</pre>',
    print_r(array_unique($arr), true)
);

// ! 2. 统计
echo "统计<br>";
echo count($arr);

function sum(...$args)
{

    // return array_reduce($args, function ($acc, $cur) {
    //     return $acc + $cur;
    // }, 0);

    return array_sum($args);
}

echo sum(1, 2, 3, 4, 5, 6, 7);  // 15

echo '<hr>乘积:';

function mul(...$args)
{
    // return array_reduce($args, function ($acc, $cur) {
    //     return $acc * $cur;
    // }, 1);

    return array_product($args);
}

echo mul(2, 3, 4, 5);  // 24
demo3:栈与队: 一个增删元素受限的数组(线性表)
<?php
// 栈与队: 一个增删元素受限的数组(线性表)
// 1. 栈操作:
// 仅限在尾部进行增删
$stack = [];
array_push($stack, 10);
printf('<pre>%s</pre>', print_r($stack, true));
array_push($stack, 20, 30);
printf('<pre>%s</pre>', print_r($stack, true));
echo array_pop($stack)."<br>";
echo array_pop($stack)."<br>";
echo array_pop($stack)."<br>";
printf('<pre>%s</pre>', print_r($stack, true));
// 仅限头部增删
array_unshift($stack, 10);
printf('<pre>%s</pre>', print_r($stack, true));
array_unshift($stack, 30, 20);
printf('<pre>%s</pre>', print_r($stack, true));
echo array_shift($stack)."<br>";
echo array_shift($stack)."<br>";
echo array_shift($stack)."<br>";

// 2. 队: 尾部添加, 头部删除
$queue = [];
// 入队
array_push($queue, 10, 20, 30);

printf('<pre>%s</pre>', print_r($queue, true));

// 出队
echo array_shift($queue)."<br>";
echo array_shift($queue)."<br>";
echo array_shift($queue)."<br>";
printf('<pre>%s</pre>', print_r($queue, true));


//  头部添加, 尾部删除
// array_unshift() +  array_pop()
demo4:数组排序
<?php
// ! 值
echo "值<br>";
$arr = [30, 4, 82, 15, 20, 'abc', 'hello', 2, 46];
printf('原始:<pre>%s</pre>', print_r($arr, true));
//升序
echo "升序<br>";
sort($arr);
echo "确保原关系不变, 原来的键与值的对应不发生变化<br>";
asort($arr);
printf('升序:<pre>%s</pre>', print_r($arr, true));

echo "降序<br>";
rsort($arr);
arsort($arr);
printf('升序:<pre>%s</pre>', print_r($arr, true));

// ! 键
echo "键<br>";
$arr = ['e' => 10, 'a' => 30, 'p' => 50];
// ksort($arr);
krsort($arr);
printf('降序:<pre>%s</pre>', print_r($arr, true));

// 打乱
echo "打乱<br>";
$blue = range(1, 16); // [1,2,3,4,5,6....... 16]
shuffle($blue);
printf('<pre>%s</pre>', print_r($blue, true));
demo5:查询与替换
<?php
echo "查询与替换<br>";
// 查询与替换
// array_slice
echo "array_slice<br>";
$stu = ['id' => 101, 'name' => '无忌', 'age' => 20, 'course' => 'php', 'grade' => 80];
printf('<pre>%s</pre>', print_r($stu, true));
echo "前2个<br>";
$res = array_slice($stu, 0, 2);
printf('<pre>%s</pre>', print_r($res, true));
echo "后2个<br>";

$res = array_slice($stu, -2, 2);
$res = array_slice($stu, -2);
printf('<pre>%s</pre>', print_r($res, true));

echo "array_splice<br>";

$arr = [10, 28, 9, 33, 56, 21, 82, 47];
printf('<pre>%s</pre>', print_r($arr, true));
echo "删除: 第2个位置删除2个<br>";

$res = array_splice($arr, 1, 2);
printf('<pre>%s</pre>', print_r($res, true));
printf('<pre>%s</pre>', print_r($arr, true));
echo "更新: 第2个位置删除2个,使用新的数据来替换掉它<br>";

$res = array_splice($arr, 1, 2, ['hello', 'world']);
printf('<pre>%s</pre>', print_r($res, true));
printf('<pre>%s</pre>', print_r($arr, true));
echo "添加: 第2个位置删除0个,传入的新数据会追加到当前位置的后面<br>";
$res = array_splice($arr, 1, 0, ['hello', 'world']);
printf('<pre>%s</pre>', print_r($res, true));
printf('<pre>%s</pre>', print_r($arr, true));
 
demo6:数组回调函数
<?php
// 数组回调函数
// 回调: 回头再调用, 函数的调用,依赖一个外部条件/事件

echo "回调函数过滤数组中的元素<br>";
// !过滤器
// array_filter: 仅返回数组中可转为true的元素集合
$arr = [
    150,
    'php',
    true,
    [4, 5, 6],
    (new class
    {
    }),
    [],
    null,
    false,
    '',
    0,
    '0'
];
$res = array_filter($arr, function ($item) {
    if ($item) {
        return is_scalar($item);
    }
});
printf('<pre>%s</pre>', print_r($res, true));

// map
echo "map<br>";
echo "将数组的每个元素发送到用户自定义的函数中进行修改或处理<br>";

$arr = ['php', [3, 4, 5], (new class
{
    public $name = '电脑';
    public $price = 8888;
}), 15, 20];
printf('<pre>%s</pre>', print_r($arr, true));

// Array
// (
//     [0] => php
//     [1] => '3,4,5'
//     [2] => '电脑,8888'
//     [3] => 15
//     [4] => 20
// )
$res = array_map(function ($item) {
    switch (gettype($item)) {
        case 'array':
            $item = join(', ', $item);
            break;
        case 'object':
            $item =  join(', ', get_object_vars($item));
    }
    return $item;
}, $arr);
printf('<pre>%s</pre>', print_r($res, true));

//
echo "3. 归并<br>";
$arr = [10, 20, 30, 40, 50];
$res = array_reduce($arr, function ($acc, $cur) {
    echo $acc, ', ', $cur, '<br>';
    return $acc + $cur;
}, 0);

echo $res . '<hr>';


echo "4. array_walk<br>";
echo "array_walk用回调函数处理数组中的各个元素, array_map和 array_walk的区别在于有无key的存在,其他都差不多<br>";

$user = ['id' => 10, 'name' => 'admin', 'email' => 'admin@php.cn'];
array_walk($user, function ($value, $key, $color) {
    printf('[%s]=><span style="color:%s">%s</span>', $key, $color, $value);
}, 'blue');
Name:
<提交>