Skip to content

Instantly share code, notes, and snippets.

@barokurniawan
Created August 23, 2021 00:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barokurniawan/8506ed6d8c500f01c9251055ae80d60b to your computer and use it in GitHub Desktop.
Save barokurniawan/8506ed6d8c500f01c9251055ae80d60b to your computer and use it in GitHub Desktop.
Convert nested object into nested array
<?php
use ReflectionClass;
class Helper
{
public static function toRupiah($number, bool $withPrefix = true)
{
return ($withPrefix ? "Rp " : "") . number_format($number, 0, ",", ".");
}
public static function toArrayDeep($obj)
{
if (is_object($obj)) $obj = (array) self::dismount($obj);
if (is_array($obj)) {
$new = array();
foreach ($obj as $key => $val) {
$new[$key] = self::toArrayDeep($val);
}
} else $new = $obj;
return $new;
}
private static function dismount($object)
{
$reflectionClass = new ReflectionClass(get_class($object));
$array = array();
foreach ($reflectionClass->getProperties() as $property) {
$property->setAccessible(true);
$array[$property->getName()] = $property->getValue($object);
$property->setAccessible(false);
}
return $array;
}
}
// use :
// $obj = /** your nested object */;
// $yourNestedArray = Helper::toArrayDeep($obj);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment