Преобразование массива в объект в PHP. Как скопировать массив в PHP
В этой статье поговорим, как преобразовать массив в объект и как создать ссылку на массив и скопировать его. Начнём с преобразования — здесь нам поможет приведение массива к типу object. Как только мы выполним преобразование массива в тип object, произойдёт создание нового экземпляра встроенного в PHP класса stdClass.
1. Преобразование массива
Итак, представьте, что у нас есть ассоциативный массив, и мы желаем преобразовать его в объект.
php // наш исходный массив $array = array( 0 => 'Вселенная', 'galaxy' => 'Млечный путь', 'planetary-system' => 'Солнечная система', 'planet' => 'Земля', 'continent' => 'Европа', 'country' => 'Россия', 'city' => 'Москва' ); // приведём массив к типу object $object = (object)$array; // выведем массив print_r($object);
Теперь посмотрим на stdClass
stdClass Object ( [0] => Вселенная [galaxy] => Млечный путь [planetary-system] => Солнечная система [planet] => Земля [continent] => Европа [country] => Россия [city] => Москва )Обращаемся к членам объекта в PHP
После выполнения преобразования ряд элементов нашего объекта (бывшего массива) мы можем получить как член класса, если они отвечают правилам именования переменной (тут следует понимать, что правильное имя должно начинаться с буквы либо символа подчеркивания, а также состоять из цифр, букв и символов подчеркивания в любом количестве).
php // бывший элемент $array['galaxy'] echo $object->galaxy; // Млечный путь
Переменное имя свойства
Если ключ нашего элемента содержал другие символы (допустим, дефис), получить значение мы сможем лишь при помощи переменного имени свойства.
php echo $object->"planetary-system">; // Солнечная система // либо так $key = "planetary-system"; echo $object->$key; // Солнечная система
Числовые ключи
Если же ключ был числовым, получить значение из объекта в PHP мы можем лишь при помощи итераций foreach :
php foreach ($object as $key => $value) echo $key . ': ' . $value . '
'; >0: Вселенная (Universe) galaxy: Млечный путь (Milky way) planetary-system: Солнечная система (Solar system) planet: Земля (Earth) continent: Европа (Europe) country: Россия (Russia) city: Москва (Moscow)2. Создание ссылки и копирование массива
Теперь перейдём ко второй части нашей статьи. На самом деле, скопировать массив в PHP несложно:
php $array = array("one", "two", "three"); print_r($array); $new_array = $array; unset($array[0]); echo "
"; print_r($new_array); ?>
Смотрим результат:
Что касается создания ссылки на массив в PHP, то нам надо всего лишь добавить амперсант:
php $array = array("one", "two", "three"); print_r($array); $new_array = &$array; unset($array[0]); echo "
"; print_r($new_array); ?>
На этом всё, приобрести более глубокие навыки PHP-программирования вы сможете на наших курсах:
ArrayObject::getArrayCopy
Returns a copy of the array. When the ArrayObject refers to an object, an array of the properties of that object will be returned.
Examples
Example #1 ArrayObject::getArrayCopy() example
// Array of available fruits
$fruits = array( "lemons" => 1 , "oranges" => 4 , "bananas" => 5 , "apples" => 10 );?php
$fruitsArrayObject = new ArrayObject ( $fruits );
$fruitsArrayObject [ 'pears' ] = 4 ;// create a copy of the array
$copy = $fruitsArrayObject -> getArrayCopy ();
print_r ( $copy );The above example will output:
Array ( [lemons] => 1 [oranges] => 4 [bananas] => 5 [apples] => 10 [pears] => 4 )User Contributed Notes 5 notes
If you did something like this to make your constructor multidimensional capable you will have some trouble using getArrayCopy to get a plain array straight out of the method:
public function __construct ( $array = array(), $flags = 2 )
// let’s give the objects the right and not the inherited name
$class = get_class ( $this );foreach( $array as $offset => $value )
$this -> offsetSet ( $offset , is_array ( $value ) ? new $class ( $value ) : $value );$this -> setFlags ( $flags );
>
?>That’s the way I solved it:
public function getArray ( $recursion = false )
// just in case the object might be multidimensional
if ( $this === true )
return $this -> getArrayCopy ();return array_map ( function( $item ) return is_object ( $item ) ? $item -> getArray ( true ) : $item ;
>, $this -> getArrayCopy () );
>
?>Hope this was useful!
$data = $likeArray -> getArrayCopy ();
?>
will NOT be magically called if you cast to array. Although I've expected it.
$nothing = (array) $likeArray ;
?>
Here, $data != $nothing.?php"When the ArrayObject refers to an object an array of the public properties of that object will be returned."
This description does not seem to be right:
class A
public $var = 'var' ;
protected $foo = 'foo' ;
private $bar = 'bar' ;
>$o = new ArrayObject (new A ());
var_dump ( $o -> getArrayCopy ());array(3) ["var"]=>
string(3) "var"
["*foo"]=>
string(3) "foo"
["Abar"]=>
string(3) "bar"
>
*/
?>So it does not only include the public properties.
Is there a difference between casting to an array and using this function?
For instance, if we have:
$arrayObject = new ArrayObject([1, 2, 3]);Is there a difference between these:
$array = (array) $arrayObject;
vs
$array = $arrayObject->getArrayCopy();If not, is there any scenario where they would produce different results, or do they produce the result in different ways?
When I used print_r ($fruitsArrayObject) instead of print_r ($copy), i.e. ignoring the getArrayCopy() step, I still got the same output. Why?