php obj to array

Fast PHP Object to Array conversion

A couple of months ago, I found a forgotten feature of PHP itself.

Apparently, it is possible to cast objects to arrays like following:

This will produce something like:

Private and Protected properties

If we start adding private and protected properties to our Foo class, things get very interesting:

The output will be like following in this case:

Let’s try accessing those keys:

Something even more strange happens here: we get two notices.

I actually spent some time trying to understand why this was happening, and even the debugger was failing me! Then I tried using var_export :

The output is quite interesting:

Null characters are used as delimiters between the visibility scope of a particular property and its name!

That’s some really strange results, and they give us some insight on how PHP actually keeps us from accessing private and protected properties.

Direct property read attempt

Looks like the engine was patched after PHP 5.1 to fix this (un-documented break), since we get a fatal:

Too bad! That would have had interesting use cases. The change makes sense though, since we shouldn’t modify internal state without explicitly using an API that cries out «I do things with your objects state!».

Some notes and suggestions

I’m currently writing a small library called GeneratedHydrator to take advantage of this behaviour and the one that I described in my previous blog post. That should prevent you from doing this kind of dangerous things with PHP 🙂

Источник

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

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

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

27 ответов

просто typecast это

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

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

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

вывод (с \ 0s отредактировано для ясности):

выход с var_export вместо var_dump :

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

вы можете быстро преобразовать глубоко вложенные объекты в ассоциативные массивы, полагаясь на поведение функций кодирования/декодирования JSON:

С первого хита Google для»объект php для массива assoc» у нас есть это:

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

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

Источник

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

php obj to array. Смотреть фото php obj to array. Смотреть картинку php obj to array. Картинка про php obj to array. Фото php obj to array

Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

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.

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.

Example Defining a Class and its Objects

php obj to array. Смотреть фото php obj to array. Смотреть картинку php obj to array. Картинка про php obj to array. Фото php obj to array

// Members of class Jobs

// Creating three objects of Jobs

$software = new Jobs;

$pharmaceutical = new Jobs;

Array

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

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.

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

Syntax:

Program:

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

echo “Before conversion :”.’ ’;

echo “After conversion :”.’ ’;

Output:

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.

Syntax:

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

Program:

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

echo “Before conversion:”.’ ’;

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

echo “After conversion:”.’ ’;

Output:

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:

php obj to array. Смотреть фото php obj to array. Смотреть картинку php obj to array. Картинка про php obj to array. Фото php obj to array

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.

Conclusion

In this article, we have introduced one of the most prominent topics of PHP. As a programmer, you will be dealing with every aspect of the language and have to work on some of the most complicated PHP concepts when moving to the advanced level. Hope this article highlighting the methods for converting an object to array in PHP will prove out to be a reference point for you.

Источник

Как преобразовать массив в объект в PHP?

Как я могу преобразовать такой массив в объект?

30 ответов:

в простейшем случае, вероятно, достаточно «бросить» массив в качестве объекта:

как Эдсон Медина указал, действительно чистое решение заключается в использовании встроенного json_ функции:

Это также (рекурсивно) преобразует все ваши суб массивы в объекты, которые вы можете или может не хочу. К сожалению, он имеет 2-3x производительность над циклическим подходом.

предупреждение! (спасибо Ultra за комментарий):

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

подделка реального объекта:

преобразуйте массив в объект, приведя его к объекту:

вручную преобразовать массив в объект:

не очень красиво, но работает.

но это не то, что вы хотите. Если вам нужны объекты, вы хотите чего-то достичь, но этого не хватает в этом вопросе. Использование объектов только по причине использования объектов не имеет смысла.

его путь к простому, это создаст объект для рекурсивных массивов, а также:

В зависимости от того, где вам это нужно и как получить доступ к объекту есть разные способы сделать это.

например: просто наберите его

однако наиболее совместимым является использование служебного метода (еще не являющегося частью PHP), который реализует стандартное PHP-кастинг на основе строки, указывающей тип (или игнорируя его, просто снимая ссылку на значение):

пример использования в вашем случае (онлайн Демо):

использование :

возвращает :

как обычно, вы можете зациклить его так:

там нет встроенного метода, чтобы сделать это, насколько я знаю, но это так же просто, как простой цикл:

вы можете изложить это, если вам нужно построить свой объект рекурсивно.

на самом деле, если вы хотите использовать это с многомерными массивами, вы хотели бы использовать некоторую рекурсию.

Я бы определенно пошел с чистым способом, как это:

Если вы представите:

php obj to array. Смотреть фото php obj to array. Смотреть картинку php obj to array. Картинка про php obj to array. Фото php obj to array

php obj to array. Смотреть фото php obj to array. Смотреть картинку php obj to array. Картинка про php obj to array. Фото php obj to array

Я нашел это более логичным, сравнивая приведенные выше ответы от объектов, которые должны использоваться для той цели, для которой они были сделаны (инкапсулированные милые маленькие объекты).

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

Источник

Php obj to array

class foo
<
function do_foo ()
<
echo «Doing foo.» ;
>
>

For a full discussion, see the Classes and Objects chapter.

Converting to object

For any other value, a member variable named scalar will contain the value.

User Contributed Notes 28 notes

By far the easiest and correct way to instantiate an empty generic php object that you can then modify for whatever purpose you choose:

In PHP 7 there are a few ways to create an empty object:

= new \ stdClass ; // Instantiate stdClass object
$obj2 = new class<>; // Instantiate anonymous class
$obj3 = (object)[]; // Cast empty array to object

As of PHP 5.4, we can create stdClass objects with some properties and values using the more beautiful form:

Here a new updated version of ‘stdObject’ class. It’s very useful when extends to controller on MVC design pattern, user can create it’s own class.

echo «‘ ;
?>
works and displays:
stdClass Object
(
[a] => A
[b] => B
[0] => C
)

/**
* Used for checking empty objects/array
* @uses How to check empty objects and array in php code
* @author Aditya Mehrotra
*/

/**
* Empty class
*/
class EmptyClass <

$obj = new stdClass ();
//or any other class empty object
$emptyClassObj = new EmptyClass ();
$array = array();

//Result SET 1
//array is empty => expected result
//object is not empty => ouch what happened
//EmptyClass is not empty => ouch what happened

/**
* So what we do for checking empty object
* @solution use any known property or check property count
* Or you can use below method
* Count function will not return 0 in empty object
*/

//Result SET 2
//array is empty => expected result ##everything is all right
//object is empty => expected result ##everything is all right
//EmptyClass is empty => expected result ##everything is all right

If you use new to create items in an array, you may not get the results you want since the parameters to array will be copies of the original and not references.

This is extremely important if you intend on passing arrays of classes to functions and expect them to always use the same object instance!

Note: The following syntax is desired (or maybe even the default notation should translate as this):
$a = array( &new Store() );

Do you remember some JavaScript implementations?

// var timestamp = (new Date).getTime();

Now it’s possible with PHP 5.4.*;

print (new Foo )-> a ; // I’m a!
print (new Foo )-> getB (); // I’m b!
?>

or

In response to sirbinam.
You cannot call a function or method before it exists. In your example, the global instance of stdout is just being passed around to differnet references (pointers). It however exists in the «dump» function scope via the global keyword.

The code below works fine and illustrates that «stdout» has been defined before its instantiation.

?>

All classes and functions declarations within a scope exist even before the php execution reaches them. It does not matter if you have your classes defined on the first or last line, as long as they are in the same scope as where they are called and are not in a conditional statement that has not been evaluated yet.

If you need to force json_encode() to produce an object even when an array is empty or does not have successive 0-based numeric indices, you can simply convert the array to an object. JSON_FORCE_OBJECT does the same with ALL arrays, which might not be what you want.

echo json_encode ([[]]), «\n» ;
// output: [[]]

echo json_encode ([[]], JSON_FORCE_OBJECT ), «\n» ;
// output: <"0":<>>

echo json_encode ([(object)[]]), «\n» ;
// output: [<>]

in php 7.2 this code works despite documentation said it gives false

= (object) array( ‘1’ => ‘foo’ );

In PHP 5+, objects are passed by reference. This has got me into trouble in the past when I’ve tried to make arrays of objects.
For example, I once wrote something like the following code, thinking that I’d get an array of distinct objects. However, this is wrong. This code will create an array of multiple references to the same object.

notice that the value at each index in the array is the same. That is because the array is just 3 references to the same object, but we change the property of this object every time the for loop runs. This isn’t very useful. Instead, I’ve changed the code below so that it will create an array with three distinct references to three distinct objects. (if you’re having a hard time understanding references, think of this as an array of objects, and that this is just the syntax you have to use.)

Notice how the creation of a new object («$arrayItem = new myNumber();») must happen every time the for loop runs for this to work.
This took me forever to figure out, so I hope this helps someone else.

PHP supports recursive type definitions as far as I’ve tried. The class below (a _very_ simple tree) is an example:

As you can see, in addChild we reference Tree again.

However, you must be careful about references. See the chapter «References explained» for more details.

If you call var_export() on an instance of stdClass, it attempts to export it using ::__set_state(), which, for some reason, is not implemented in stdClass.

However, casting an associative array to an object usually produces the same effect (at least, it does in my case). So I wrote an improved_var_export() function to convert instances of stdClass to (object) array () calls. If you choose to export objects of any other class, I’d advise you to implement ::__set_state().

/* Output:
(object) array (‘prop1’ => true, ‘prop2’ => (object) array (‘test’ => ‘abc’, ‘other’ => 6.2, ‘arr’ => array (0 => 1, 1 => 2, 2 => 3)), ‘assocArray’ => array (‘apple’ => ‘good’, ‘orange’ => ‘great’))
*/
?>

Note: This function spits out a single line of code, which is useful to save in a cache file to include/eval. It isn’t formatted for readability. If you want to print a readable version for debugging purposes, then I would suggest print_r() or var_dump().

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *