0
0

Collection.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: zhangyajun <448901948@qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace think;
  12. use ArrayAccess;
  13. use ArrayIterator;
  14. use Countable;
  15. use IteratorAggregate;
  16. use JsonSerializable;
  17. class Collection implements ArrayAccess, Countable, IteratorAggregate, JsonSerializable
  18. {
  19. /**
  20. * 数据集数据
  21. * @var array
  22. */
  23. protected $items = [];
  24. public function __construct($items = [])
  25. {
  26. $this->items = $this->convertToArray($items);
  27. }
  28. public static function make($items = [])
  29. {
  30. return new static($items);
  31. }
  32. /**
  33. * 是否为空
  34. * @access public
  35. * @return bool
  36. */
  37. public function isEmpty()
  38. {
  39. return empty($this->items);
  40. }
  41. public function toArray()
  42. {
  43. return array_map(function ($value) {
  44. return ($value instanceof Model || $value instanceof self) ? $value->toArray() : $value;
  45. }, $this->items);
  46. }
  47. public function all()
  48. {
  49. return $this->items;
  50. }
  51. /**
  52. * 合并数组
  53. *
  54. * @access public
  55. * @param mixed $items
  56. * @return static
  57. */
  58. public function merge($items)
  59. {
  60. return new static(array_merge($this->items, $this->convertToArray($items)));
  61. }
  62. /**
  63. * 交换数组中的键和值
  64. *
  65. * @access public
  66. * @return static
  67. */
  68. public function flip()
  69. {
  70. return new static(array_flip($this->items));
  71. }
  72. /**
  73. * 按指定键整理数据
  74. *
  75. * @access public
  76. * @param mixed $items 数据
  77. * @param string $indexKey 键名
  78. * @return array
  79. */
  80. public function dictionary($items = null, &$indexKey = null)
  81. {
  82. if ($items instanceof self || $items instanceof Paginator) {
  83. $items = $items->all();
  84. }
  85. $items = is_null($items) ? $this->items : $items;
  86. if ($items && empty($indexKey)) {
  87. $indexKey = is_array($items[0]) ? 'id' : $items[0]->getPk();
  88. }
  89. if (isset($indexKey) && is_string($indexKey)) {
  90. return array_column($items, null, $indexKey);
  91. }
  92. return $items;
  93. }
  94. /**
  95. * 比较数组,返回差集
  96. *
  97. * @access public
  98. * @param mixed $items 数据
  99. * @param string $indexKey 指定比较的键名
  100. * @return static
  101. */
  102. public function diff($items, $indexKey = null)
  103. {
  104. if ($this->isEmpty() || is_scalar($this->items[0])) {
  105. return new static(array_diff($this->items, $this->convertToArray($items)));
  106. }
  107. $diff = [];
  108. $dictionary = $this->dictionary($items, $indexKey);
  109. if (is_string($indexKey)) {
  110. foreach ($this->items as $item) {
  111. if (!isset($dictionary[$item[$indexKey]])) {
  112. $diff[] = $item;
  113. }
  114. }
  115. }
  116. return new static($diff);
  117. }
  118. /**
  119. * 比较数组,返回交集
  120. *
  121. * @access public
  122. * @param mixed $items 数据
  123. * @param string $indexKey 指定比较的键名
  124. * @return static
  125. */
  126. public function intersect($items, $indexKey = null)
  127. {
  128. if ($this->isEmpty() || is_scalar($this->items[0])) {
  129. return new static(array_diff($this->items, $this->convertToArray($items)));
  130. }
  131. $intersect = [];
  132. $dictionary = $this->dictionary($items, $indexKey);
  133. if (is_string($indexKey)) {
  134. foreach ($this->items as $item) {
  135. if (isset($dictionary[$item[$indexKey]])) {
  136. $intersect[] = $item;
  137. }
  138. }
  139. }
  140. return new static($intersect);
  141. }
  142. /**
  143. * 返回数组中所有的键名
  144. *
  145. * @access public
  146. * @return array
  147. */
  148. public function keys()
  149. {
  150. $current = current($this->items);
  151. if (is_scalar($current)) {
  152. $array = $this->items;
  153. } elseif (is_array($current)) {
  154. $array = $current;
  155. } else {
  156. $array = $current->toArray();
  157. }
  158. return array_keys($array);
  159. }
  160. /**
  161. * 删除数组的最后一个元素(出栈)
  162. *
  163. * @access public
  164. * @return mixed
  165. */
  166. public function pop()
  167. {
  168. return array_pop($this->items);
  169. }
  170. /**
  171. * 通过使用用户自定义函数,以字符串返回数组
  172. *
  173. * @access public
  174. * @param callable $callback
  175. * @param mixed $initial
  176. * @return mixed
  177. */
  178. public function reduce(callable $callback, $initial = null)
  179. {
  180. return array_reduce($this->items, $callback, $initial);
  181. }
  182. /**
  183. * 以相反的顺序返回数组。
  184. *
  185. * @access public
  186. * @return static
  187. */
  188. public function reverse()
  189. {
  190. return new static(array_reverse($this->items));
  191. }
  192. /**
  193. * 删除数组中首个元素,并返回被删除元素的值
  194. *
  195. * @access public
  196. * @return mixed
  197. */
  198. public function shift()
  199. {
  200. return array_shift($this->items);
  201. }
  202. /**
  203. * 在数组结尾插入一个元素
  204. * @access public
  205. * @param mixed $value
  206. * @param mixed $key
  207. * @return void
  208. */
  209. public function push($value, $key = null)
  210. {
  211. if (is_null($key)) {
  212. $this->items[] = $value;
  213. } else {
  214. $this->items[$key] = $value;
  215. }
  216. }
  217. /**
  218. * 把一个数组分割为新的数组块.
  219. *
  220. * @access public
  221. * @param int $size
  222. * @param bool $preserveKeys
  223. * @return static
  224. */
  225. public function chunk($size, $preserveKeys = false)
  226. {
  227. $chunks = [];
  228. foreach (array_chunk($this->items, $size, $preserveKeys) as $chunk) {
  229. $chunks[] = new static($chunk);
  230. }
  231. return new static($chunks);
  232. }
  233. /**
  234. * 在数组开头插入一个元素
  235. * @access public
  236. * @param mixed $value
  237. * @param mixed $key
  238. * @return void
  239. */
  240. public function unshift($value, $key = null)
  241. {
  242. if (is_null($key)) {
  243. array_unshift($this->items, $value);
  244. } else {
  245. $this->items = [$key => $value] + $this->items;
  246. }
  247. }
  248. /**
  249. * 给每个元素执行个回调
  250. *
  251. * @access public
  252. * @param callable $callback
  253. * @return $this
  254. */
  255. public function each(callable $callback)
  256. {
  257. foreach ($this->items as $key => $item) {
  258. $result = $callback($item, $key);
  259. if (false === $result) {
  260. break;
  261. } elseif (!is_object($item)) {
  262. $this->items[$key] = $result;
  263. }
  264. }
  265. return $this;
  266. }
  267. /**
  268. * 用回调函数处理数组中的元素
  269. * @access public
  270. * @param callable|null $callback
  271. * @return static
  272. */
  273. public function map(callable $callback)
  274. {
  275. return new static(array_map($callback, $this->items));
  276. }
  277. /**
  278. * 用回调函数过滤数组中的元素
  279. * @access public
  280. * @param callable|null $callback
  281. * @return static
  282. */
  283. public function filter(callable $callback = null)
  284. {
  285. if ($callback) {
  286. return new static(array_filter($this->items, $callback));
  287. }
  288. return new static(array_filter($this->items));
  289. }
  290. /**
  291. * 根据字段条件过滤数组中的元素
  292. * @access public
  293. * @param string $field 字段名
  294. * @param mixed $operator 操作符
  295. * @param mixed $value 数据
  296. * @return static
  297. */
  298. public function where($field, $operator, $value = null)
  299. {
  300. if (is_null($value)) {
  301. $value = $operator;
  302. $operator = '=';
  303. }
  304. return $this->filter(function ($data) use ($field, $operator, $value) {
  305. if (strpos($field, '.')) {
  306. list($field, $relation) = explode('.', $field);
  307. $result = isset($data[$field][$relation]) ? $data[$field][$relation] : null;
  308. } else {
  309. $result = isset($data[$field]) ? $data[$field] : null;
  310. }
  311. switch (strtolower($operator)) {
  312. case '===':
  313. return $result === $value;
  314. case '!==':
  315. return $result !== $value;
  316. case '!=':
  317. case '<>':
  318. return $result != $value;
  319. case '>':
  320. return $result > $value;
  321. case '>=':
  322. return $result >= $value;
  323. case '<':
  324. return $result < $value;
  325. case '<=':
  326. return $result <= $value;
  327. case 'like':
  328. return is_string($result) && false !== strpos($result, $value);
  329. case 'not like':
  330. return is_string($result) && false === strpos($result, $value);
  331. case 'in':
  332. return is_scalar($result) && in_array($result, $value, true);
  333. case 'not in':
  334. return is_scalar($result) && !in_array($result, $value, true);
  335. case 'between':
  336. list($min, $max) = is_string($value) ? explode(',', $value) : $value;
  337. return is_scalar($result) && $result >= $min && $result <= $max;
  338. case 'not between':
  339. list($min, $max) = is_string($value) ? explode(',', $value) : $value;
  340. return is_scalar($result) && $result > $max || $result < $min;
  341. case '==':
  342. case '=':
  343. default:
  344. return $result == $value;
  345. }
  346. });
  347. }
  348. /**
  349. * 返回数据中指定的一列
  350. * @access public
  351. * @param mixed $columnKey 键名
  352. * @param mixed $indexKey 作为索引值的列
  353. * @return array
  354. */
  355. public function column($columnKey, $indexKey = null)
  356. {
  357. return array_column($this->toArray(), $columnKey, $indexKey);
  358. }
  359. /**
  360. * 对数组排序
  361. *
  362. * @access public
  363. * @param callable|null $callback
  364. * @return static
  365. */
  366. public function sort(callable $callback = null)
  367. {
  368. $items = $this->items;
  369. $callback = $callback ?: function ($a, $b) {
  370. return $a == $b ? 0 : (($a < $b) ? -1 : 1);
  371. };
  372. uasort($items, $callback);
  373. return new static($items);
  374. }
  375. /**
  376. * 指定字段排序
  377. * @access public
  378. * @param string $field 排序字段
  379. * @param string $order 排序
  380. * @param bool $intSort 是否为数字排序
  381. * @return $this
  382. */
  383. public function order($field, $order = null, $intSort = true)
  384. {
  385. return $this->sort(function ($a, $b) use ($field, $order, $intSort) {
  386. $fieldA = isset($a[$field]) ? $a[$field] : null;
  387. $fieldB = isset($b[$field]) ? $b[$field] : null;
  388. if ($intSort) {
  389. return 'desc' == strtolower($order) ? $fieldB >= $fieldA : $fieldA >= $fieldB;
  390. } else {
  391. return 'desc' == strtolower($order) ? strcmp($fieldB, $fieldA) : strcmp($fieldA, $fieldB);
  392. }
  393. });
  394. }
  395. /**
  396. * 将数组打乱
  397. *
  398. * @access public
  399. * @return static
  400. */
  401. public function shuffle()
  402. {
  403. $items = $this->items;
  404. shuffle($items);
  405. return new static($items);
  406. }
  407. /**
  408. * 截取数组
  409. *
  410. * @access public
  411. * @param int $offset
  412. * @param int $length
  413. * @param bool $preserveKeys
  414. * @return static
  415. */
  416. public function slice($offset, $length = null, $preserveKeys = false)
  417. {
  418. return new static(array_slice($this->items, $offset, $length, $preserveKeys));
  419. }
  420. // ArrayAccess
  421. public function offsetExists($offset)
  422. {
  423. return array_key_exists($offset, $this->items);
  424. }
  425. public function offsetGet($offset)
  426. {
  427. return $this->items[$offset];
  428. }
  429. public function offsetSet($offset, $value)
  430. {
  431. if (is_null($offset)) {
  432. $this->items[] = $value;
  433. } else {
  434. $this->items[$offset] = $value;
  435. }
  436. }
  437. public function offsetUnset($offset)
  438. {
  439. unset($this->items[$offset]);
  440. }
  441. //Countable
  442. public function count()
  443. {
  444. return count($this->items);
  445. }
  446. //IteratorAggregate
  447. public function getIterator()
  448. {
  449. return new ArrayIterator($this->items);
  450. }
  451. //JsonSerializable
  452. public function jsonSerialize()
  453. {
  454. return $this->toArray();
  455. }
  456. /**
  457. * 转换当前数据集为JSON字符串
  458. * @access public
  459. * @param integer $options json参数
  460. * @return string
  461. */
  462. public function toJson($options = JSON_UNESCAPED_UNICODE)
  463. {
  464. return json_encode($this->toArray(), $options);
  465. }
  466. public function __toString()
  467. {
  468. return $this->toJson();
  469. }
  470. /**
  471. * 转换成数组
  472. *
  473. * @access public
  474. * @param mixed $items
  475. * @return array
  476. */
  477. protected function convertToArray($items)
  478. {
  479. if ($items instanceof self) {
  480. return $items->all();
  481. }
  482. return (array) $items;
  483. }
  484. }