Skip to content

Commit b2931ef

Browse files
committed
🔨 improve on objectify() function to work on arrays recursively
Signed-off-by: otengkwame <[email protected]>
1 parent 188b476 commit b2931ef

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed

Core/helpers/webby_helper.php

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1210,23 +1210,42 @@ function arrayfy($object, $asGenerator = false, $threshold = 1000)
12101210

12111211
if ( ! function_exists('objectify'))
12121212
{
1213+
12131214
/**
1214-
* Encode an array and retrieve
1215+
* Convert an array and retrieve
12151216
* as an object
12161217
*
12171218
* @param array $array
1218-
* @return object|bool
1219+
* @param bool $natural
1220+
* @param string|object $class
1221+
* @return object|mixed
12191222
*/
1220-
function objectify(array $array)
1223+
function objectify(array $array, $natural = false, $class = 'stdClass')
12211224
{
1225+
1226+
if ($natural) {
1227+
1228+
$object = new $class;
1229+
1230+
foreach ($array as $key => $value) {
1231+
if (is_array($value)) {
1232+
// Recursively convert nested arrays
1233+
$object->$key = objectify($value, true, $class);
1234+
} else {
1235+
$object->$key = $value;
1236+
}
1237+
}
1238+
1239+
return $object;
1240+
}
1241+
12221242
if (is_array($array)) {
12231243
$array = json_encode($array, JSON_THROW_ON_ERROR);
12241244
return json_decode($array, null, 512, JSON_THROW_ON_ERROR);
12251245
}
12261246

12271247
throw new \Exception("Parameter must be array", 1);
1228-
1229-
return false;
1248+
12301249
}
12311250
}
12321251

0 commit comments

Comments
 (0)