Php foreach object to array

victorbstan / php_object_to_array.php

This file contains 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

/*
This function saved my life.
found on: http://www.sitepoint.com/forums//showthread.php?t=438748
by: crvandyke
It takes an object, and when all else if/else/recursive functions fail to convert the object into an associative array, this one goes for the kill. Who would’a thunk it?!
*/
$ array = json_decode(json_encode( $ object ), true );

Do you know how many times I’ve had to do this over the past few years and it was ugly. This is definitely a life saver!

Exactly what I was looking for. Give this man a beer.

Just tried over some nested objects/array and it didn’t work.
But this does (not as elegant, but more effective):

`private function object_to_array($obj) if(is_object($obj)) $obj = (array) $this->dismount($obj);
if(is_array($obj)) $new = array();
foreach($obj as $key => $val) $new[$key] = $this->object_to_array($val);
>
>
else $new = $obj;
return $new;
>

//permet de changer les private en public, pour un meuilleur conversion des object en array
private 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;
>`

@TwanoO67 I had the same issue when converting an array to object using the code below. It only converted the outer most array to object and not the nested arrays.

$object = json_decode(json_encode($array), false); 
$object = json_decode(json_encode($array, JSON_FORCE_OBJECT), false); 

I’m pretty sure the solution would be similar when converting from object to array.

Источник

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

В этой статье показано, как преобразовать объект в массив в PHP.

1. Использование приведения типов

Простым вариантом преобразования объекта в ассоциативный массив является приведение типов. Чтобы привести объект к массиву, вы можете просто указать тип массива в круглых скобках перед объектом для преобразования. Когда объект PHP преобразуется в ассоциативный массив, все свойства объекта становятся элементами массива. Например, следующее решение отбрасывает StdClass объект в массив:

Следующее решение приводит объект, имеющий только общедоступные свойства.

Как видно из приведенных выше примеров, приведение типов хорошо работает с StdClass и класс для всех общедоступных свойств. Если ваш объект содержит какие-либо закрытые поля, ключи массива будут включать область видимости. Частные и защищенные свойства будут иметь имя класса и ‘*’ перед именем элемента соответственно. Обратите внимание, что имя класса и ‘*’ разделены нулевым символом ( «\0» ) с обеих сторон, как показано ниже:

2. Использование get_object_vars() функция

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

3. Использование отражения

Вы можете использовать Reflection для доступа к закрытым и защищенным полям вне области действия объекта. В этом примере используется ReflectionClass::getProperties() для извлечения отраженных свойств и сохранения их в массиве. В отличие от приведения типов, это решение приводит к правильным именам ключей для непубличных полей. До PHP 8.1.0 вы должны вызывать ReflectionProperty::setAccessible() для обеспечения доступа к защищенной или частной собственности. Начиная с PHP 8.1.0 все свойства доступны по умолчанию.

Источник

3 Ways – Convert a PHP Object to an Array and Vice-Versa

DISCLOSURE: This article may contain affiliate links and any sales made through such links will reward us a small commission, at no extra cost for you. Read more about Affiliate Disclosure here.

Objects and arrays are essential parts of our day to day programming. PHP object to array and array to object conversions are quite common requirements. We are mentioning three ways that you can use to convert PHP object to an array.

Vice-versa, if you’re seeking for the reverse procedure, i.e. converting an array to object then here is the link of the article. There are methods for the array to object conversion that work on a multidimensional array as well.

Convert a PHP Object to an Array

1. Typecasting Object to Array

Either object to array or array to object conversion, typecasting is the easiest solution if the input is well-structured. By well-structured means, the input has valid keys. Below is the code to typecast and convert the object to the array.

2. Convert PHP Object to Array with JSON Functions

PHP’s JSON functions can also do the object to the array or vice-versa conversion smartly. Additionally, it works perfectly with nested objects to convert them as an associative array. This is the best solution if you want a full depth recursive conversion.

First, the json_encode() function converts the object into JSON string. Further, the second parameter in json_decode() function tells PHP to convert the encoded string to an associative array.

Despite the way you use to convert PHP object to the array, also take care of a few things. For a smooth conversion, always:

  • Avoid creating StdClass object with integer properties. They become quite inaccessible even you can see them using print_r() or similar.
  • Declare objects as public members of the class. Otherwise, the array keys will have weird and dirty notations. You can check about them at the official website for PHP.

3. Object to Array Conversion using get_object_vars()

Turning an object to an array using get_object_vars() is a lesser-known yet a quite good method. Also, the popular blogging platform WordPress uses it heavily. A good example of the object to array conversion is given below:

So you see that the get_object_vars() function returns an associative array of a defined object accessible in the scope. Also, it doesn’t take non-static properties for the specified object in the account. Additionally, if a property contains no value, it will be returned with a NULL value.

Other Ways for Converting PHP Object to Array

Finally, those above are the 3 preferred ways we wanted to share to convert a PHP object to an array. Indeed, there are other ways too for the same. Object iteration through a foreach loop or using PHP’s Reflection API and recursive function calls are a few of them.

However, we haven’t discussed them here in details because personally, we don’t like long lines of code for general needs. Still, they might be useful in hacky cases. So it’s worth to provide the code for them.

Источник

How to Convert Object to Array in PHP [With Example]

PHP is one of the most popular general-purpose scripting languages used widely for web development. It is one of the fastest and flexible programming languages. Working with PHP is all about dealing with data types. There are several data types in PHP in which objects and arrays are the composite data types of PHP. This article is centred on how to convert an object to array in PHP .

Check out our free courses to get an edge over the competition.

Object-Oriented Programming (OOP) in PHP

One of the key aspects of PHP is object-oriented programming where the data is treated as an object, and software is implemented on it. This is one of the simplified approaches of advanced PHP. Object-oriented programming is achievable with PHP where objects have rules defined by a PHP program they are running in. These rules are called the classes. They are very important if you are looking to convert object to array in PHP.

Some OOP Concepts

Before getting into how objects are converted into arrays, let’s first learn about some important terms related to object-oriented programming in PHP.

Class

Classes are the data types defined by a programmer. It includes local function and local data. A class can serve as a template for making multiple instances of the same class of objects.

Object

An individual instance of the data structure is defined by a class. Many objects belonging to a class can be made after defining a class once. Objects are also called as instances.

Check out upGrad’s Java Bootcamp

Example Defining a Class and its Objects

// Creating three objects of Jobs

Array

An array, in PHP, is a special kind of variable that holds more than one value at a time.

In-Demand Software Development Skills

Defining an Array

In PHP, the array is defined with the array function ‘array()’.

$numbers = array(“One”, “Two”, “Three”);

Object to Array PHP

There are mainly two methods by which an object is converted into an array in PHP:

1. By typecasting object to array PHP

2. Using the JSON Decode and Encode Method

Let’s have a look at both in detail:

1. Typecasting Object to Array PHP

Typecasting is a method where one data type variable is utilized into a different data type, and it is simply the exact conversion of a data type. It is also one of the most used methods of converting an object to array in PHP .

In PHP, an object can be converted to an array with the typecasting rules of PHP.

public function __inventory( $product1, $product2, $product3)

$myShop= new shop(“Grocery”, “Cosmetic”, “Grain”);

Before conversion:

object(shop)#1 (3) < [“product1″]=>string(5) ” Grocery ” [“product2″]=> string(4) ” Cosmetic ” [“product3″]=> string(4) ” Grain ” >

After conversion:

array(3) < [“product1″]=>string(5) ” Grocery ” [“product2″]=> string(4) ” Cosmetic ” [“product3″]=> string(4) ” Grain ” >

Explanation of the program:

In the above program, a class “shop” is created. In the ‘shop’ class, the function ‘inventory()’ is created. The function inventory() will be executed when an object is created.

The constructor will receive arguments provided when the object is created with a new keyword. In the first var_dump() expression, the object is printed. The second time, the object is type casted into an array using the type-casting procedure.

2. Using the JSON Decode and Encode Method

Object to array PHP is also done with the JSON decode and encode method. In this method, the json_encode() function returns a JSON encoded string for a given value. The json_decode() function accepts the JSON encoded string and converts it into a PHP array. This is a very popular method used to convert object to array PHP .

$myArray = json_decode(json_encode($object), true);

public function __company($firstname, $lastname)

$myObj = new employee(“Carly”, “Jones”);

$myArray = json_decode(json_encode($myObj), true);

Before conversion:

object(student)#1 (2) < [“firstname”]=>string(4) ” Carly ” [“lastname”]=> string(6) ” Jones ” >

After conversion:

array(2) < [“firstname”]=>string(4) ” Carly ” [“lastname”]=> string(6) ” Jones ” >

Explanation of the program:

In the program above, a class with the name ‘employee’ is created. In that class, a function ‘company()’ is declared which will be executed during the creation of the object.

The constructor receives the arguments given when creating the object using a new keyword. In the first var_dump() expression, the object is printed and in the second, the object is converted into an array using json_decode and json_encode technique.

How to create an Object from Array in PHP

PHP object to array and how to convert object to array PHP have been covered. We will now examine how to build an object from an array. You are free to use any of the distinct examples mentioned above for PHP object to array to do this in order to meet the demands of your own code.

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Use json_decode and json_encode Method

The json decode() and json encode() methods in PHP may be used to create an object from an array, similar to changing an object to an array PHP . The array is first produced, and then it is transformed into an object. The array is transformed into an object using –

$object = json_decode (json_encode ($array))

The output is then printed out using –

function var_dump(variable of the object)

//Convert array into an object

//Print array as an object using

Источник

Читайте также:  Python windows console program
Оцените статью