ใน PHP ต้องการแปลง Object เป็น Associative Array บ่อยครั้ง มี 2 วิธีหลัก:
วิธีที่ 1: json_decode + json_encode
json_encode() แปลง object เป็น JSON string json_decode() แปลง JSON string เป็น array (พารามิเตอร์ true)
ตัวอย่าง
<?php
class student {
public function __construct($firstname, $lastname) {
$this->firstname = $firstname;
$this->lastname = $lastname;
}
}
$myObj = new student("Alex", "Stokes");
echo "Before conversion:";
var_dump($myObj);
$myArray = json_decode(json_encode($myObj), true);
echo "After conversion:";
var_dump($myArray);
?>
ผลลัพธ์
Before conversion: object(student)#1 (2) { ["firstname"]=> string(4) "Alex" ["lastname"]=> string(6) "Stokes" }
After conversion: array(2) { ["firstname"]=> string(4) "Alex" ["lastname"]=> string(6) "Stokes" }
วิธีที่ 2: Type Casting
แปลง object เป็น array โดย type casting: (array)$object
<?php
class bag {
public function __construct($item1, $item2, $item3){
$this->item1 = $item1;
$this->item2 = $item2;
$this->item3 = $item3;
}
}
$myBag = new bag("Books", "Ball", "Pens");
echo "Before conversion:";
var_dump($myBag);
$myBagArray = (array)$myBag;
echo "After conversion:";
var_dump($myBagArray);
?>
ผลลัพธ์
Before conversion: object(bag)#1 (3) { ["item1"]=> string(5) "Books" ["item2"]=> string(4) "Ball" ["item3"]=> string(4) "Pens" }
After conversion: array(3) { ["item1"]=> string(5) "Books" ["item2"]=> string(4) "Ball" ["item3"]=> string(4) "Pens" }