Files
newspage/classes/Application/Helper/ArrayPath.php
2024-10-07 22:58:27 +02:00

83 lines
2.0 KiB
PHP

<?php
namespace Application\Helper;
use Exception;
/**
* Return data from a nested array by providing a path. The parts of the path are seperated by commas.
*
* Examples: 'this.is.a.path' | 'root-node'
*/
class ArrayPath {
/**
* Return array data by given paths.
*
* Accepts no key (return all data) or a string (one specific data) or array (returns multiple data).
*
* @throws Exception|Exception
*/
public static function GetDataFromArray(array $array, mixed $key = null): mixed {
if (!$key) {
return $array;
}
if (is_string($key) and strpos($key, '.')) {
return self::getArrayDataByPath($array, $key);
}
if (is_string($key) and array_key_exists($key, $array)) {
return $array[$key];
}
if (is_array($key)) {
return self::GetMultipleData($array, $key);
}
return null;
}
/**
* Get data from a nested array by providing a path.
*
* @param string|array $data array to search the data on (haystack)
* @param string|array $path path(s) with dot-seperated parts (needle(s))
*
* @return mixed
*/
private static function getArrayDataByPath(mixed $data, string|array $path): mixed {
if (is_string($path)) {
$path = explode('.', $path);
}
if (count($path) === 0) {
return $data;
}
$key = array_shift($path);
return isset($data[$key]) ? self::getArrayDataByPath($data[$key], $path) : '';
}
/**
* Return multiple data by providing an array of desired keys and not just one as a string.
*
* @param array $data Haystack
* @param array $key Needles
*
* @return array
* @throws Exception
*/
private static function GetMultipleData(array $data, array $key): array {
$return = array();
foreach ($key as $key_value) {
$return[$key_value] = self::GetDataFromArray($data, $key_value);
}
return $return;
}
}