72 lines
2.1 KiB
PHP
72 lines
2.1 KiB
PHP
<?php
|
|
|
|
if (! function_exists('array_to_object_2025')) {
|
|
/**
|
|
* A magic function that turns all nested array into nested objects. Calling it with no parameter would result in a empty object.
|
|
*
|
|
* @param mixed $array The array to be recursively casted into an object.
|
|
* @return \stdClass|null Returns null if the given parameter is not either an array or an object.
|
|
*/
|
|
function array_to_object_2025($array = []): ?stdClass
|
|
{
|
|
if (is_object($array)) {
|
|
return $array;
|
|
}
|
|
|
|
if (! is_array($array)) {
|
|
return null;
|
|
}
|
|
|
|
$object = new \stdClass;
|
|
|
|
if (! isset($array) || empty($array)) {
|
|
return $object;
|
|
}
|
|
|
|
foreach ($array as $k => $v) {
|
|
if (mb_strlen($k)) {
|
|
if (is_array($v)) {
|
|
if (array_is_assoc($v)) {
|
|
// Convert associative arrays to objects
|
|
$object->{$k} = array_to_object_2025($v);
|
|
} else {
|
|
// For indexed arrays, keep them as arrays but process their elements
|
|
$object->{$k} = [];
|
|
foreach ($v as $idx => $item) {
|
|
if (is_array($item)) {
|
|
$object->{$k}[$idx] = array_to_object_2025($item);
|
|
} else {
|
|
$object->{$k}[$idx] = $item;
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
$object->{$k} = $v;
|
|
}
|
|
}
|
|
}
|
|
|
|
return $object;
|
|
}
|
|
}
|
|
|
|
if (! function_exists('array_is_assoc')) {
|
|
/**
|
|
* Determines whether or not an array is an associative array.
|
|
*
|
|
* @param array $array The array to be evaluated.
|
|
*/
|
|
function array_is_assoc($array): bool
|
|
{
|
|
if (! is_array($array)) {
|
|
return false;
|
|
}
|
|
|
|
if ($array === []) {
|
|
return false;
|
|
}
|
|
|
|
return array_keys($array) !== range(0, count($array) - 1);
|
|
}
|
|
}
|