分类目录归档:Php

计算一个数字能拆分计算的次数

编写一个函数persistence,它接受一个正参数num并返回其乘法持久性,即必须将num中的数字相乘到一个数字的次数。这是codewars上的一道习题,感觉挺有意思的。
示例:
persistence(39) === 3; // because 3 * 9 = 27, 2 * 7 = 14, 1 * 4 = 4 and 4 has only one digit
persistence(999) === 4; // because 9 * 9 * 9 = 729, 7 * 2 * 9 = 126, 1 * 2 * 6 = 12, and finally 1 * 2 = 2
persistence(4) === 0; // because 4 is already a one-digit number

代码:

function persistence(int $num): int {
   if($num<10) return 0;
        $split_arr = str_split($num);
        $res = array_product($split_arr);
        return 1+persistence($res);

}
0

call_user_func使用范例

/**
 * Class my_class
 */
class my_class {
    /**
     * @param $name
     */
    static function say_hello($name)
    {
        echo "Hello,".$name."\n";
    }
}

$classname = "my_class";
call_user_func([$classname,'say_hello'],'damon');
call_user_func($classname."::say_hello",'connie');

$myObj = new my_class();
call_user_func([$myObj,'say_hello'],'Jerry');
1+

array_reduce的用法

$employees = [
    [
        'name' => 'damon',
        'age' => 34,
        'email' => 'yank@qq.com',
    ],
    [
        'name' => 'connie',
        'age' => 33,
        'email' => 'connie@qq.com',
    ],
    [
        'name' => 'jerry',
        'age' => 7,
        'email' => 'jerry@qq.com',
    ]
];


$emails = array_reduce($employees,function ($carry,$item){
    $carry[$item['name']] = $item['email'];
    return $carry;
},[]);

dd($emails);

print result:

array:3 [▼
  "damon" => "yank@qq.com"
  "connie" => "connie@qq.com"
  "jerry" => "jerry@qq.com"
]
0

用一层循环找出数组当中两两相加等于100的数

这是昨天碰到的面试题,不得不承认直接想有点想不出来,用代码实现其实还好。

<?php

    $sourceArr = [56,10,20,50,50,70,30,44];
    $tmpArr = [];

    foreach ($sourceArr as $key => $value) {
        if(isset($tmpArr[100 - $value])){
            echo $value.'---'.$tmpArr[100 - $value]."<br/>";
        }else{
            $tmpArr[$value] = $value;
        }
    }

结果:

50---50
30---70
44---56
2+

Composer常用命令

  • php package仓库:https://packagist.org/
命令描述
composer search xxxx搜索包
composer show -i查看当前安装的包
composer show -a xxx/xxx显示详情
composer install安装(默认安装composer.lock)
composer install –no-dev安装(忽略require-dev)
composer update更新包(重新生成composer.lock)
composer dump-autoload生成autoload文件
composer init初始化composer项目

使用composer自动加载类文件

建立composer.json文件指定src文件夹的命名空间

    {
      "autoload":{
        "psr-4":{
          "App\\":"src/"
        }
      }
    }

生成自动加载文件

    composer dump-autoload

引入自动加载文件

    require_once 'vendor/autoload.php';
0