一个php链式操作的demo
<?php /** * 该类的目标不是写一个排序,而是怎样实现一个链式操作 * 提供了两种排序方法,可以任意使用,体现出链式操作的方便性 */ class chain{ /** * 要排序的数组 */ protected $arr = []; /** * 排序类型,正序和倒序,asc正序,desc倒序 */ protected $type = "asc"; /** * 得到数据源 +----------------------------------------- * @param array $arr 得到要排序的数组 * @return this */ public function data($arr){ $this->arr = $arr; return $this; } /** * 实现排序规则 +----------------------------------------------- * @param int $type 排序规则,0为倒序,1为正序 * @return this */ public function order($type){ $this->type = $type; return $this; } /** * 处理排序功能,冒泡排序法 */ public function bubble(){ for($i = 0,$k = count($this->arr); $i < $k; $i++) { for ($j = $i + 1;$j < $k; $j++) { if($this->type == 'desc'){ if($this->arr[$i] < $this->arr[$j]){ $temp = $this->arr[$j]; $this->arr[$j] = $this->arr[$i]; $this->arr[$i] = $temp; } }else{ if($this->arr[$i] > $this->arr[$j]){ $temp = $this->arr[$j]; $this->arr[$j] = $this->arr[$i]; $this->arr[$i] = $temp; } } } } return $this->arr; } /** * 使用PHP内置函数排序 */ public function sorts(){ if($this->type == 'desc'){ arsort($this->arr); }else{ asort($this->arr); } return $this->arr; } } $chain = new chain(); $result = $chain->data([10,27,3,55,67,125,7,99,6,8])->order("asc")->sorts(); print_r($result);
相关推荐
-
PHP列出一个目录所有文件和文件夹 php
2019-1-8
-
php上传图片生成缩略图 php
2019-1-8
-
php无限分类 php
2019-1-7
-
php 图像处理 抠图,生成背景透明png 图片 php
2019-1-7
-
递归和非递归遍历文件夹下文件 php
2019-1-7
-
PHP获取接下来一周的日期 php
2019-1-7
-
PHP中的环境变量 php
2019-1-7
-
求两个已知经纬度之间的距离,单位为米geo php
2019-1-8
-
PHP异步 php
2019-1-7
-
一个php链式操作的demo php
2019-1-7