summaryrefslogtreecommitdiffstats
path: root/inc/arrayutil.inc.php
blob: 490b5a4fa17577466eae50957b65ce73b49c4d25 (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
<?php

class ArrayUtil
{

	/**
	 * Take an array of arrays, take given key from each sub-array and return
	 * new array with just those corresponding values.
	 * @param array $list
	 * @param string $key
	 * @return array
	 */
	public static function flattenByKey(array $list, string $key)
	{
		$ret = [];
		foreach ($list as $item) {
			if (array_key_exists($key, $item)) {
				$ret[] = $item[$key];
			}
		}
		return $ret;
	}

	/**
	 * 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.
	 * @param array $arrays
	 * @return array
	 */
	public static function mergeByKey(array $arrays)
	{
		$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;
	}

}