summaryrefslogtreecommitdiffstats
path: root/inc/arrayutil.inc.php
blob: 3d93d7d5c08051d41d0027ef5f4ec0426e8c9c13 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php

declare(strict_types=1);

class ArrayUtil
{

	/**
	 * Take an array of arrays, take given key from each sub-array and return
	 * new array with just those corresponding values.
	 */
	public static function flattenByKey(array $list, string $key): array
	{
		return array_column($list, $key);
	}

	/**
	 * Pass an array of arrays you want to merge. The keys of the outer array will become
	 * the inner keys of the resulting array, and vice versa.
	 */
	public static function mergeByKey(array $arrays): array
	{
		$empty = array_combine(array_keys($arrays), array_fill(0, count($arrays), false));
		$out = [];
		foreach ($arrays as $subkey => $array) {
			foreach ($array as $key => $item) {
				if (!isset($out[$key])) {
					$out[$key] = $empty;
				}
				$out[$key][$subkey] = $item;
			}
		}
		return $out;
	}

	/**
	 * Sort array by given column.
	 */
	public static function sortByColumn(array &$array, string $column, int $sortOrder = SORT_ASC, int $sortFlags = SORT_REGULAR): void
	{
		$sorter = array_column($array, $column);
		array_multisort($sorter, $sortOrder, $sortFlags, $array);
	}

	/**
	 * Check whether $array contains all keys given in $keyList
	 *
	 * @param array $array An array
	 * @param array $keyList A list of strings which must all be valid keys in $array
	 */
	public static function hasAllKeys(array $array, array $keyList): bool
	{
		foreach ($keyList as $key) {
			if (!isset($array[$key]))
				return false;
		}
		return true;
	}

	/**
	 * Check if all elements in given array are primitive types,
	 * i.e. not object, array or resource.
	 */
	public static function isOnlyPrimitiveTypes(array $array): bool
	{
		foreach ($array as $item) {
			if (is_array($item) || is_object($item) || is_resource($item))
				return false;
		}
		return true;
	}

	/**
	 * Force each element of given array to be of type $type.
	 */
	public static function forceType(array &$array, string $type): void
	{
		foreach ($array as &$elem) {
			settype($elem, $type);
		}
	}

}