ArrayHelper.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Bear
  5. * Date: 2018/11/15
  6. * Time: 下午4:59
  7. */
  8. namespace app\main\helper;
  9. class ArrayHelper
  10. {
  11. /**
  12. * 组装wherein的参数值
  13. * @param $list
  14. * @return string
  15. */
  16. public static function getWhereInValue($list)
  17. {
  18. if (!$list) {
  19. return 'null';
  20. }
  21. return implode(',', $list);
  22. }
  23. public static function array_get($array, $key, $default = '')
  24. {
  25. if (array_key_exists($key, $array)) {
  26. return $array[$key];
  27. }
  28. return $default;
  29. }
  30. /**
  31. * @param string $match
  32. * @param array $arr
  33. * @return bool
  34. */
  35. public static function match($match, array $arr)
  36. {
  37. if (!$arr) {
  38. return false;
  39. }
  40. // 是否存在
  41. if (in_array(strtolower($match), $arr) || in_array('*', $arr)) {
  42. return true;
  43. }
  44. // 没找到匹配
  45. return false;
  46. }
  47. public static function array_fetch($array, $keys, $default = '')
  48. {
  49. $result = [];
  50. $keys = (array)$keys;
  51. foreach ($keys as $key) {
  52. if (array_key_exists($key, $array)) {
  53. $result[$key] = $array[$key];
  54. } else {
  55. $result[$key] = $default;
  56. }
  57. }
  58. return $result;
  59. }
  60. /**
  61. * Indexes and/or groups the array according to a specified key.
  62. * The input should be either multidimensional array or an array of objects.
  63. *
  64. * The $key can be either a key name of the sub-array, a property name of object, or an anonymous
  65. * function that must return the value that will be used as a key.
  66. *
  67. * $groups is an array of keys, that will be used to group the input array into one or more sub-arrays based
  68. * on keys specified.
  69. *
  70. * If the `$key` is specified as `null` or a value of an element corresponding to the key is `null` in addition
  71. * to `$groups` not specified then the element is discarded.
  72. *
  73. * For example:
  74. *
  75. * ```php
  76. * $array = [
  77. * ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
  78. * ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
  79. * ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
  80. * ];
  81. * $result = ArrayHelper::index($array, 'id');
  82. * ```
  83. *
  84. * The result will be an associative array, where the key is the value of `id` attribute
  85. *
  86. * ```php
  87. * [
  88. * '123' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop'],
  89. * '345' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
  90. * // The second element of an original array is overwritten by the last element because of the same id
  91. * ]
  92. * ```
  93. *
  94. * An anonymous function can be used in the grouping array as well.
  95. *
  96. * ```php
  97. * $result = ArrayHelper::index($array, function ($element) {
  98. * return $element['id'];
  99. * });
  100. * ```
  101. *
  102. * Passing `id` as a third argument will group `$array` by `id`:
  103. *
  104. * ```php
  105. * $result = ArrayHelper::index($array, null, 'id');
  106. * ```
  107. *
  108. * The result will be a multidimensional array grouped by `id` on the first level, by `device` on the second level
  109. * and indexed by `data` on the third level:
  110. *
  111. * ```php
  112. * [
  113. * '123' => [
  114. * ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
  115. * ],
  116. * '345' => [ // all elements with this index are present in the result array
  117. * ['id' => '345', 'data' => 'def', 'device' => 'tablet'],
  118. * ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone'],
  119. * ]
  120. * ]
  121. * ```
  122. *
  123. * The anonymous function can be used in the array of grouping keys as well:
  124. *
  125. * ```php
  126. * $result = ArrayHelper::index($array, 'data', [function ($element) {
  127. * return $element['id'];
  128. * }, 'device']);
  129. * ```
  130. *
  131. * The result will be a multidimensional array grouped by `id` on the first level, by the `device` on the second one
  132. * and indexed by the `data` on the third level:
  133. *
  134. * ```php
  135. * [
  136. * '123' => [
  137. * 'laptop' => [
  138. * 'abc' => ['id' => '123', 'data' => 'abc', 'device' => 'laptop']
  139. * ]
  140. * ],
  141. * '345' => [
  142. * 'tablet' => [
  143. * 'def' => ['id' => '345', 'data' => 'def', 'device' => 'tablet']
  144. * ],
  145. * 'smartphone' => [
  146. * 'hgi' => ['id' => '345', 'data' => 'hgi', 'device' => 'smartphone']
  147. * ]
  148. * ]
  149. * ]
  150. * ```
  151. *
  152. * @param array $array the array that needs to be indexed or grouped
  153. * @param string|\Closure|null $key the column name or anonymous function which result will be used to index the array
  154. * @param string|string[]|\Closure[]|null $groups the array of keys, that will be used to group the input array
  155. * by one or more keys. If the $key attribute or its value for the particular element is null and $groups is not
  156. * defined, the array element will be discarded. Otherwise, if $groups is specified, array element will be added
  157. * to the result array without any key. This parameter is available since version 2.0.8.
  158. * @return array the indexed and/or grouped array
  159. */
  160. public static function index($array, $key, $groups = [])
  161. {
  162. $result = [];
  163. $groups = (array) $groups;
  164. foreach ($array as $element) {
  165. $lastArray = &$result;
  166. foreach ($groups as $group) {
  167. $value = static::getValue($element, $group);
  168. if (!array_key_exists($value, $lastArray)) {
  169. $lastArray[$value] = [];
  170. }
  171. $lastArray = &$lastArray[$value];
  172. }
  173. if ($key === null) {
  174. if (!empty($groups)) {
  175. $lastArray[] = $element;
  176. }
  177. } else {
  178. $value = static::getValue($element, $key);
  179. if ($value !== null) {
  180. if (is_float($value)) {
  181. $value = StringHelper::floatToString($value);
  182. }
  183. $lastArray[$value] = $element;
  184. }
  185. }
  186. unset($lastArray);
  187. }
  188. return $result;
  189. }
  190. /**
  191. * Retrieves the value of an array element or object property with the given key or property name.
  192. * If the key does not exist in the array, the default value will be returned instead.
  193. * Not used when getting value from an object.
  194. *
  195. * The key may be specified in a dot format to retrieve the value of a sub-array or the property
  196. * of an embedded object. In particular, if the key is `x.y.z`, then the returned value would
  197. * be `$array['x']['y']['z']` or `$array->x->y->z` (if `$array` is an object). If `$array['x']`
  198. * or `$array->x` is neither an array nor an object, the default value will be returned.
  199. * Note that if the array already has an element `x.y.z`, then its value will be returned
  200. * instead of going through the sub-arrays. So it is better to be done specifying an array of key names
  201. * like `['x', 'y', 'z']`.
  202. *
  203. * Below are some usage examples,
  204. *
  205. * ```php
  206. * // working with array
  207. * $username = \yii\helpers\ArrayHelper::getValue($_POST, 'username');
  208. * // working with object
  209. * $username = \yii\helpers\ArrayHelper::getValue($user, 'username');
  210. * // working with anonymous function
  211. * $fullName = \yii\helpers\ArrayHelper::getValue($user, function ($user, $defaultValue) {
  212. * return $user->firstName . ' ' . $user->lastName;
  213. * });
  214. * // using dot format to retrieve the property of embedded object
  215. * $street = \yii\helpers\ArrayHelper::getValue($users, 'address.street');
  216. * // using an array of keys to retrieve the value
  217. * $value = \yii\helpers\ArrayHelper::getValue($versions, ['1.0', 'date']);
  218. * ```
  219. *
  220. * @param array|object $array array or object to extract value from
  221. * @param string|\Closure|array $key key name of the array element, an array of keys or property name of the object,
  222. * or an anonymous function returning the value. The anonymous function signature should be:
  223. * `function($array, $defaultValue)`.
  224. * The possibility to pass an array of keys is available since version 2.0.4.
  225. * @param mixed $default the default value to be returned if the specified array key does not exist. Not used when
  226. * getting value from an object.
  227. * @return mixed the value of the element if found, default value otherwise
  228. */
  229. public static function getValue($array, $key, $default = null)
  230. {
  231. if ($key instanceof \Closure) {
  232. return $key($array, $default);
  233. }
  234. if (is_array($key)) {
  235. $lastKey = array_pop($key);
  236. foreach ($key as $keyPart) {
  237. $array = static::getValue($array, $keyPart);
  238. }
  239. $key = $lastKey;
  240. }
  241. if (is_array($array) && (isset($array[$key]) || array_key_exists($key, $array))) {
  242. return $array[$key];
  243. }
  244. if (($pos = strrpos($key, '.')) !== false) {
  245. $array = static::getValue($array, substr($key, 0, $pos), $default);
  246. $key = substr($key, $pos + 1);
  247. }
  248. if (is_object($array)) {
  249. // this is expected to fail if the property does not exist, or __get() is not implemented
  250. // it is not reliably possible to check whether a property is accessible beforehand
  251. return $array->$key;
  252. } elseif (is_array($array)) {
  253. return (isset($array[$key]) || array_key_exists($key, $array)) ? $array[$key] : $default;
  254. }
  255. return $default;
  256. }
  257. /**
  258. * 在数组中按字段查找元素
  259. * @param array $arr 待查找的数组
  260. * @param string $colName 字段
  261. * @param $colValue 匹配的值,完全匹配
  262. * @param bool $findOne 是否只返回第一个匹配到的值
  263. * @return array|mixed
  264. */
  265. public static function array_column_search(array $arr, $colName, $colValue, $findOne = true)
  266. {
  267. if (count($arr) == 0) {
  268. return [];
  269. }
  270. $result = [];
  271. if ($findOne) {
  272. foreach ($arr as $item) {
  273. if ($item[$colName] == $colValue) {
  274. return $item;
  275. }
  276. }
  277. } else {
  278. foreach ($arr as $item) {
  279. if ($item[$colName] == $colValue) {
  280. $result[] = $item;
  281. }
  282. }
  283. }
  284. return $result;
  285. }
  286. /**
  287. * 截取二维数组的指定字段
  288. * @param $array
  289. * @param $colmns
  290. * @return array
  291. */
  292. public static function extractColumn($array, $colmns)
  293. {
  294. $return = [];
  295. foreach ($array as $item) {
  296. $tmp = [];
  297. foreach($colmns as $key=>$colmn){
  298. if (array_key_exists($colmn, $item)) {
  299. $tmp[$colmn] = $item[$colmn];
  300. }else{
  301. $tmp[$colmn] = '';
  302. }
  303. }
  304. $return[] = $tmp;
  305. }
  306. return $return;
  307. }
  308. /**
  309. * 两个数组的值做减法,挑选出存在于A,但不存在于B的元素
  310. * @param $vectorA
  311. * @param $vectorB
  312. * @return array
  313. */
  314. public static function restaDeArrays($vectorA, $vectorB)
  315. {
  316. $cantA = count($vectorA);
  317. $cantB = count($vectorB);
  318. $No_saca = 0;
  319. for ($i = 0; $i < $cantA; $i++) {
  320. for ($j = 0; $j < $cantB; $j++) {
  321. if ($vectorA[$i] == $vectorB[$j]) {
  322. $No_saca = 1;
  323. }
  324. }
  325. if ($No_saca == 0) {
  326. $nuevo_array[] = $vectorA[$i];
  327. } else {
  328. $No_saca = 0;
  329. }
  330. }
  331. return $nuevo_array;
  332. }
  333. /**
  334. * 数组元素叠加
  335. * @param $ini
  336. * @param $append
  337. * @return mixed
  338. */
  339. public static function array_plus($ini, $append)
  340. {
  341. foreach ($append as $key => $value) {
  342. if (array_key_exists($key, $ini)) {
  343. $ini[$key] += $value;
  344. } else {
  345. $ini[$key] = $value;
  346. }
  347. }
  348. return $ini;
  349. }
  350. public static function array_random(array $array)
  351. {
  352. $array = array_values($array);
  353. return $array[mt_rand(0, count($array) - 1)];
  354. }
  355. /**
  356. * 查询数组中是否含有指定key,不存在返回空
  357. * @param $array
  358. * @param $key
  359. * @return mixed|string
  360. */
  361. public static function array_find($array, $key)
  362. {
  363. if (!$array) {
  364. return '';
  365. }
  366. if (array_key_exists($key, $array)) {
  367. return $array[$key];
  368. }
  369. $fields = explode('.', $key);
  370. if (count($fields) > 1) {
  371. if (array_key_exists($fields[0], $array)) {
  372. $first = array_shift($fields);
  373. return self::array_find($array[$first], implode('.', $fields));
  374. }
  375. }
  376. return '';
  377. }
  378. public static function array_replace_key($array, $replace)
  379. {
  380. foreach ($array as $field => $value) {
  381. if (array_key_exists($field, $replace)) {
  382. unset($array[$field]);
  383. $array[$replace[$field]] = $value;
  384. }
  385. }
  386. return $array;
  387. }
  388. }