Преобразование объекта PHP в массив с использованием декодирования JSON
Преобразование объекта PHP в массив упрощает доступ к данным из пакета объектов. Большинство API выводит объект в качестве ответа.
Некоторые API могут возвращать сложную структуру объекта. Например, смесь объектов и массивов в комплекте с ответом. В то время процесс преобразования объекта в массив упростит анализ данных.
Преобразование объекта PHP в массив в строке с использованием json_decode
<?php $object = new StdClass(); $object->id = 5678; $object->name = "William"; $object->department = "CSE"; $object->designation = "Engineer"; $result = json_encode($object); // converts object $result to array $output = json_decode($result, true); print "<pre>"; print_r($result); ?>
Приведение типа к преобразованию объекта
<?php $object = new StdClass(); $object->id = 5678; $object->name = "William"; $object->department = "CSE"; $object->destination = "Engineer"; print"<pre>"; print_r( (array) $object ); ?>
Преобразование рекурсивного объекта в массив
<?php
$object = new StdClass();
$object->id = 5678;
$object->name = "William";
$object->address = new stdClass();
$object->address->email = "William@gmail.com";
$object->address->billing = new stdClass();
$object->address->billing->zipcode = 9950;
$object->address->shipping = new stdClass();
$object->address->shipping->zipcode = 1234;
$object->address->state = "South Carolina";
$object->address->city = "Columbia";
$object->address->country = "US";
function objectToArray($object)
{
foreach ($object as $k => $obj) {
if (is_object($obj)) {
$object->$k = objectToArray($obj);
} else {
$object->$k = $obj;
}
}
return (array) $object;
}
$result = objectToArray($object);
print "<pre>";
print_r($result);
?>
Преобразование объект класса PHP в массив
<?php
class student
{
public function __construct($id, $name, $state, $city, $country)
{
$this->id = $id;
$this->name = $name;
$this->state = $state;
$this->city = $city;
$this->country = $country;
}
}
$student = new student("5678", "William", "South Carolina", "Columbia", "US");
$result = json_encode($student);
$output = json_decode($result, true);
print "<pre>";
print_r($output);
?>
Проверка объекта перед преобразованием
<?php
class student
{
public function __construct($id, $name, $state, $city, $country)
{
$this->id = $id;
$this->name = $name;
$this->state = $state;
$this->city = $city;
$this->country = $country;
}
}
$student= new student("5678", "William", "South Carolina", "Columbia", "US");
print "<pre>";
if (is_object($student)) {
echo "Input Object:" . '<br>';
$result = json_encode($student);
print_r($result);
$studentArray = json_decode($result, true);
}
if(!empty($studentArray) && is_array($studentArray)) {
echo "<br><br>Output Array:" . '<br>';
print_r($studentArray);
}
?>
Преобразование частного, защищенного объекта класса
<?php
class Student
{
public $name;
private $id;
protected $email;
public function __construct()
{
$this->name ="William";
$this->id = 5678;
$this->email = "william@gmail.com";
}
}
print "<pre>";
$student = new Student;
$result = json_encode($student);
$output1 = json_decode($result, true);
print "<br/>Using JSON decode:<br/>";
print_r($output1);
$output2 = new Student;
print "<br/><br/>Using Type casting:<br/>";
print_r( (array) $output2 );
?>
Доступ к свойствам объекта с помощью цифровых клавиш
<?php
$inputArray = array(
'name' => 'William',
'email' => 'William@gmail.com',
'phone' => '12345678',
'REG5678'
);
$student = (object) array(
'name' => 'William',
'email' => 'William@gmail.com',
'phone' => '12345678',
'REG5678'
);
echo '<pre>' . print_r($student, true) . '</pre>';
echo '<br />' . $student->name;
echo '<br />' . $student->email;
echo '<br />' . $student->phone;
echo '<br />' . $student->{0};
?>