first commit
This commit is contained in:
71
app/Helpers/Global/cast_helpers.php
Normal file
71
app/Helpers/Global/cast_helpers.php
Normal file
@@ -0,0 +1,71 @@
|
||||
<?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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user