Merge pull request #8188 from gelysis/array-lib

Tweaks on the ArrayLib class
This commit is contained in:
Daniel Hensby 2018-06-19 15:06:39 +01:00 committed by GitHub
commit a7a45559f0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -75,28 +75,14 @@ class ArrayLib
} }
/** /**
* @todo Improve documentation * Flattens a multi-dimensional array to a one level array without preserving the keys
* *
* @param array $arr * @param array $array
* @return array * @return array
*/ */
public static function array_values_recursive($arr) public static function array_values_recursive($array)
{ {
$lst = array(); return self::flatten($array, false);
foreach (array_keys($arr) as $k) {
$v = $arr[$k];
if (is_scalar($v)) {
$lst[] = $v;
} elseif (is_array($v)) {
$lst = array_merge(
$lst,
self::array_values_recursive($v)
);
}
}
return $lst;
} }
/** /**
@ -123,25 +109,19 @@ class ArrayLib
* Determines if an array is associative by checking for existing keys via * Determines if an array is associative by checking for existing keys via
* array_key_exists(). * array_key_exists().
* *
* @see http://nz.php.net/manual/en/function.is-array.php#76188 * @see http://nz.php.net/manual/en/function.is-array.php#121692
* *
* @param array $arr * @param array $array
* *
* @return boolean * @return boolean
*/ */
public static function is_associative($arr) public static function is_associative($array)
{ {
if (is_array($arr) && !empty($arr)) { $isAssociative = !empty($array)
for ($iterator = count($arr) - 1; $iterator; $iterator--) { && is_array($array)
if (!array_key_exists($iterator, $arr)) { && ($array !== array_values($array));
return true;
}
}
return !array_key_exists(0, $arr); return $isAssociative;
}
return false;
} }
/** /**
@ -252,17 +232,18 @@ class ArrayLib
*/ */
public static function flatten($array, $preserveKeys = true, &$out = array()) public static function flatten($array, $preserveKeys = true, &$out = array())
{ {
foreach ($array as $key => $child) { array_walk_recursive(
if (is_array($child)) { $array,
$out = self::flatten($child, $preserveKeys, $out); function ($value, $key) use (&$out, $preserveKeys) {
if (!is_scalar($value)) {
// Do nothing
} elseif ($preserveKeys) {
$out[$key] = $value;
} else { } else {
if ($preserveKeys) { $out[] = $value;
$out[$key] = $child;
} else {
$out[] = $child;
}
} }
} }
);
return $out; return $out;
} }