Php exception object to array

Преобразование объекта PHP в ассоциативный массив

Я интегрирую на свой веб-сайт API, который работает с данными, хранящимися в объектах, в то время как мой код написан с использованием массивов.

Мне нужна быстрая и безопасная функция для преобразования объекта в массив.

Ответ 1

Просто введите это:

$array = (array) $yourObject;

Из документации по массивам:

Если объект преобразуется в массив, результатом будет массив, элементами которого являются свойства объекта. Ключами являются имена переменных-членов, за некоторыми примечательными исключениями: целочисленные свойства недоступны; частные переменные имеют имя класса, добавляемое к имени переменной; защищенные переменные имеют ‘*’, добавляемое к имени переменной. Эти добавленные значения имеют нулевые байты по обе стороны.

Пример: Простой объект

$object = new StdClass;

$object->foo = 1;

$object->bar = 2;

var_dump( (array) $object );

Вывод:

array(2)

‘foo’ => int(1)

‘bar’ => int(2)

>

Пример: Сложный объект

класс Foo

private $foo;

protected $bar;

public $baz;

public function __construct()

$this->foo = 1;

$this->bar = 2;

$this->baz = new StdClass;

>

>

var_dump( (array) new Foo );

Вывод (отредактированным для ясности):

array(3)

‘\0Foo\0foo’ => int(1)

‘\0*\0bar’ => int(2)

‘baz’ => class stdClass#2 (0) <>

>

Вывод с помощью var_export вместо var_dump:

array (

» . «\0» . ‘Foo’ . «\0» . ‘foo’ => 1,

» . «\0» . ‘*’ . «\0» . ‘bar’ => 2,

‘baz’ => stdClass::__set_state(array(

)),

)

Типизация таким образом не будет выполнять глубокое приведение графа объекта, и вам нужно будет применить нулевой байт (как объясняется в цитате из руководства) для доступа к любым непубличным атрибутам. Следственно , этот способ лучше всего подходит для приведения объектов StdClass или объектов, имеющих только публичные свойства. Для быстрого и безопасного (то, о чем вы просили) это подходит.

Ответ 2

Ответ 3

Если свойства вашего объекта являются общедоступными, вы можете:

$array = (array) $object;

Если же они имеют модификаторы private или protected, у них будут неопределенные имена ключей в массиве. Итак, в этом случае вам понадобится следующая функция:

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;

>

Ответ 4

class Test

const A = 1;

public $b = ‘two’;

private $c = test::A;

public function __toArray()

return call_user_func(‘get_object_vars’, $this);

>

>

$my_test = new Test();

var_dump((array)$my_test);

var_dump($my_test->__toArray());

Вывод

array(2)

[«b»] => string(3) «two» [«Testc»]=> int(1)

>

array(1)

[«b»] => string(3) «two»

>

Ответ 5

Вот код:

function object_to_array($data)

if ((! is_array($data)) and (! is_object($data)))

return ‘xxx’; // $data;

$result = array();

$data = (array) $data;

foreach ($data as $key => $value)

if (is_object($value))

$value = (array) $value;

if (is_array($value))

$result[$key] = object_to_array($value);

else

$result[$key] = $value;

>

return $result;

>

Мы будем очень благодарны

если под понравившемся материалом Вы нажмёте одну из кнопок социальных сетей и поделитесь с друзьями.

Источник

PHP object to array

PHP object to array

The following article provides an outline for PHP object to array. As we all know, object is known as a class instance which has memory allocated. In the case of an array, it is a data structure containing one or more values of a similar type in a single name. On the other hand, an associative array is not like a normal PHP array. An associative array is an array that consists of a string index which stores item values linked with key values other than in order of the linear index.

Web development, programming languages, Software testing & others

Methods of a PHP object to array

Now, let us see different ways in which we can convert PHP object to array.

Method 1

With the help of the json_decode and json_encode method

In this method, the function json_decode takes JSON encoded string and changes it into a PHP variable, whereas the json_encode function returns a string which is encoded in a json format for a particular value.

$arr = json_decode(json_encode ( $obj ) , true);

Method 2

With the help of type casting

Typecasting is a technique in which one data type variable into the another data type. It is considered as an explicit data type conversion. It can translate a PHP object to an array with the help of typecasting rules in PHP.

How to Convert an object to an array in PHP?

As we all know, there are several formats of data like strings, objects, arrays etc. In the case of PHP also, there are data formats like this. In order to get the needed output, a php object obj result is needed in a format of an associative array.

Now, let us see how to translate a php object.

 // create class object . . . // convert object to array . . . . ?>

This is the skeleton for converting an object into an array.

Now let us see how to perform this.

When the object is var_dump, all items will be displayed.

  • For decoding into an object, a json string which is available will be used to convert and string formatting is done to an object. It will be done using $obj = json_decode(json_encode($arr));
  • When the object is var_dump, all items will be displayed after converting into an array.

Here, one important point to consider is json_decode that translates a json string to an object, except you offer another option that is boolean which can be true or false. Even if the second parameter is considered as true, an array will be obtained.

Also, when json encode operation and decode operation are used, arrays are converted to objects that take up many resources if the array is large. In that case, the better method to type cast an array to an object that uses the object cast.

Consider $obj = (object) $arr; syntax. Here also, object will be converted into arrays.

Based on the requirements, you can choose the method you want for the conversion of an array into an object in PHP.

Examples of a PHP object to array

Different examples are mentioned below:

Example #1

PHP program to convert an object to an array using the typecasting method.

item1 = $dis1; $this->item2 = $dis2; $this->item3 = $dis3; > > // Creation of object for the class $dis = new hospital("D", "S", "C") ; echo "Items before conversion : " ; var_dump($dis); // convert object to array $arr = (array)$dis; echo "Items after conversion : "; var_dump($arr); ?>

PHP object to array 1

In this program, a class hospital is created, and inside that, three elements such as el1, el2, and el3. Then, a __construct() function is declared, which gets executed during the time object is created. Once this is done, the constructor takes parameters that are later offered during the object creation using the keyword “new”. From the program, it can be seen that objects get printed in the first case of expression var_dump(). But in the second case of expression, an object is casted into an array using the typecasting procedure.

Example #2

PHP program to convert an object to an array using json encode and json decode.

item1 = $dis1; $this->item2 = $dis2; > > // Creating object $dis = new hospital(500, "C"); echo "Items before conversion : " ; var_dump($dis); // convert object to array $arr = json_decode(json_encode($dis), true); echo "Items after conversion : "; var_dump($arr); ?>

PHP object to array 2

In this program also, a class hospital is created, and inside that, two elements such as el1 and el2, are created. Then, a __construct() function is declared, which gets executed during the time object is created. Once this is done, the constructor takes parameters that are later offered during the object creation using the keyword “new”. From the program, it can be seen that objects get printed in the first case of expression var_dump(). But in the second case of expression, an object is casted into an array using the typecasting procedure. Here, the first method in the method sections is used for converting an object into an array.

Conclusion

An associative array is an array that consists of a string index which stores item values linked with key values other than in order of the linear index. This article saw how PHP object to array is working, methods to achieve it, and different examples.

This is a guide to PHP object to array. Here we discuss the introduction, methods, how to convert object to array in PHP? and examples respectively. You may also have a look at the following articles to learn more –

25+ Hours of HD Videos
5 Courses
6 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

92+ Hours of HD Videos
22 Courses
2 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

83+ Hours of HD Videos
16 Courses
1 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

PHP Course Bundle — 8 Courses in 1 | 3 Mock Tests
43+ Hours of HD Videos
8 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

Источник

Читайте также:  Python обрезать число до точки
Оцените статью