Skip to content

Commit

Permalink
Array to Object method
Browse files Browse the repository at this point in the history
  • Loading branch information
phpmathan committed Jul 2, 2020
1 parent f028ba9 commit b9b4ca8
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/stdlib/src/Helper/ObjectHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use InvalidArgumentException;
use ReflectionProperty;
use stdClass;
use Throwable;
use function is_numeric;
use function json_encode;
Expand Down Expand Up @@ -174,4 +175,41 @@ public static function getDefaultValue(string $type)

return $value;
}

/**
* Converts an array into standard object.
*
* @param array
*
* @return stdClass
*/
public static function toObject(array $array): stdClass
{
$object = new \stdClass;

if (!$array) {
return $object;
}

foreach ($array as $name => $value) {
if ($name == '') {
continue;
}

$isNumericArray = false;

if ((array) $value === $value) {
foreach ($value as $k => $v) {
if (is_numeric($k)) {
$isNumericArray = true;
break;
}
}
}

$object->$name = $isNumericArray ?$value :static::toObject($value);
}

return $object;
}
}

0 comments on commit b9b4ca8

Please sign in to comment.