Php Konversi Array Menjadi Objek/Objek Menjadi Array - Dewa Blogger

Halaman

    Social Items

Buy Now

Php Konversi Array Menjadi Objek/Objek Menjadi Array

1. Array ke Objek

Fungsi

function array_to_object($array) {     if(is_array($array)) {         return (object) array_map(__FUNCTION__, $array);     } else {         return $array;     } }

Contoh Kasus

Sebelum dikonversi…

$test = array(     'A' => 'Test A',     'B' => 'Test B',     'C' => array(         'CA' => 'Test CA',         'CB' => array(             'CBA' => 'Test CBA'         )     ),     'D' => 'Test D' );  // Pemanggilan... echo $test['A']; // Hasil => `Test A` echo $test['C']['CB']; // Hasil => `Test CB` echo $test['C']['CB']['CBA']; // Hasil => `Test CBA`

Sesudah dikonversi…

...  $object_test = array_to_object($test);  // Pemanggilan... echo $object_test->A; // Hasil => `Test A` echo $object_test->C->CB; // Hasil => `Test CB` echo $object_test->C->CB->CBA; // Hasil => `Test CBA`

2. Objek ke Array

Fungsi

function object_to_array($object) {     if(is_object($object)) {         $object = get_object_vars($object);     }     if(is_array($object)) {         return array_map(__FUNCTION__, $object);     } else {         return $object;     } }

Contoh Kasus

Sebelum dikonversi…

$test = new stdClass; $test->A = 'Test A'; $test->B = 'Test B'; $test->C = new stdClass; $test->C->CA = 'Test CA'; $test->C->CB = new stdClass; $test->C->CB->CBA = 'Test CBA'; $test->D = 'Test D';  // Pemanggilan echo $test->A; // Hasil => `Test A`

Sesudah dikonversi…

...  $array_test = object_to_array($test);  // Pemanggilan echo $array_test['A']; // Hasil => `Test A`

Sumber https://www.dte.web.id/