Created
August 23, 2021 00:29
-
-
Save barokurniawan/8506ed6d8c500f01c9251055ae80d60b to your computer and use it in GitHub Desktop.
Convert nested object into nested array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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