Table of Contents
一、stdClass数组转对象
二、对象转数组
三、ArrayObject方法数组转对象
Home Backend Development PHP Tutorial PHP数组转对象的几种方法

PHP数组转对象的几种方法

Jun 20, 2016 pm 01:04 PM
php array

今天在做产品的时候无意中看到了一行代码,

$c= new$class_name;
                                                        
$object_os= newstdClass;
                                                        
$c->on_init_app_router($object_os);
Copy after login

很疑惑,于是去类$c中看了一下,发现原来是对空类stdClass的实例$object_os进行了一些属性的动态添加。

从上面的三行代码中大致能看出来stdClass能为我们做些什么。

stdClass在产品的代码中见过几次,但是自己没有用过,于是查了一下相关资料,把心得整理总结如下。

stdClass是PHP的一个基类,所有的类几乎都继承这个类,所以任何时候都可以被new,可以让这个变量成为一个object。同时,这个基类又有一个特殊的地方,就是没有方法。

stdClass是在PHP5中逐渐流行起来的,这是因为,PHP5的对象的独特性,对象在任何地方被调用,都是引用地址型的,所以相对消耗的资源会少一些。在其它页面为它赋值时是直接修改,而不是引用一个拷贝。

例如:

$user= newstdClass();
$user->name = ‘gouki’;
$myUser= $user;
$myUser->name = ‘flypig’;
Copy after login

如果在PHP4时代,这样的代码就是在消耗系统资源。因为:

$myUser= $user;
Copy after login

这是创建了一个拷贝。所以,在PHP4的时候,都是这样使用:

$myUser= & $user;
Copy after login

从文章开始的三行代码我们可以看到,stdClass可以用来生成对象类型的元素,那么接下来,我们就通过stdClass将一个数组转为为对象类引出几种数组对象相互转换的方法:

一、stdClass数组转对象

$arr= array();                                            
$arr['a'] = 1;                                               
$arr['b'] = 2;                                               
$arr['c'] = 3;                                             
                   
$object= newstdClass;
foreach($arras$key=> $value) {
    $object->$key= $value;
}
                   
var_dump($object);
Copy after login

结果输出如下:

object(stdClass)#1 (3) {
  ["a"]=>
  int(1)
  ["b"]=>
  int(2)
  ["c"]=>
  int(3)
}
Copy after login

二、对象转数组

functionobject_to_array($obj) 
{ 
    $_arr= is_object($obj) ? get_object_vars($obj) : $obj; 
    foreach($_arras$key=> $val) 
    { 
        $val= (is_array($val) || is_object($val)) ?       object_to_array($val) : $val; 
        $arr[$key] = $val; 
    } 
    return$arr; 
}
Copy after login

三、ArrayObject方法数组转对象

$arr= array('key1'=>'test1', 'key2'=> 'test2');
           
var_dump(newArrayObject($arr));
Copy after login

结果输出如下:

object(ArrayObject)#1 (1) {
  ["storage":"ArrayObject":private]=>
  array(2) {
    ["key1"]=>
    string(5) "test1"
    ["key2"]=>
    string(5) "test2"
  }
}
Copy after login

当然PHP强大灵活决定了必定还有很多其他方法进行数组与对象的转换。


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1234
24
How to use PHP arrays to generate and display charts and statistical graphs How to use PHP arrays to generate and display charts and statistical graphs Jul 15, 2023 pm 12:24 PM

How to use PHP arrays to generate and display charts and statistical graphs. PHP is a widely used server-side scripting language with powerful data processing and graphic generation capabilities. In web development, we often need to display charts and statistical graphs of data. Through PHP arrays, we can easily implement these functions. This article will introduce how to use PHP arrays to generate and display charts and statistical graphs, and provide relevant code examples. Introducing the necessary library files and style sheets Before starting, we need to introduce some necessary library files into the PHP file

How to use PHP arrays to generate dynamic slideshows and image displays How to use PHP arrays to generate dynamic slideshows and image displays Jul 15, 2023 pm 01:17 PM

How to use PHP arrays to generate dynamic slideshows and picture displays. Slideshows and picture displays are common functions in web design and are often used in scenarios such as carousels and gallery displays. As a popular server-side scripting language, PHP has the ability to process data and generate dynamic HTML pages, and is very suitable for generating dynamic slideshows and picture displays. This article will introduce how to use PHP arrays to generate dynamic slideshows and picture displays, and give corresponding code examples. Prepare image data First, we need to prepare a set of image path data

How to use PHP arrays to implement user login and permission management functions How to use PHP arrays to implement user login and permission management functions Jul 15, 2023 pm 08:55 PM

How to use PHP arrays to implement user login and permission management functions When developing a website, user login and permission management are one of the very important functions. User login allows us to authenticate users and protect the security of the website. Permission management can control users' operating permissions on the website to ensure that users can only access the functions for which they are authorized. In this article, we will introduce how to use PHP arrays to implement user login and permission management functions. We'll use a simple example to demonstrate this process. First we need to create

How to convert a two-dimensional php array into a one-dimensional array How to convert a two-dimensional php array into a one-dimensional array Aug 03, 2023 am 11:14 AM

How to convert a php array from two dimensions to a one-dimensional array: 1. Use loop traversal to traverse the two-dimensional array and add each element to the one-dimensional array; 2. Use the "array_merge" function to merge multiple arrays into An array. Pass the two-dimensional array as a parameter to the "array_merge" function to convert it into a one-dimensional array; 3. Using the "array_reduce" function, you can process all the values ​​in the array through a callback function and finally return a result.

How to determine how many arrays there are in php How to determine how many arrays there are in php Aug 04, 2023 pm 05:40 PM

There are several ways to determine an array in PHP: 1. Use the count() function, which is suitable for all types of arrays. However, it should be noted that if the parameter passed in is not an array, the count() function will return 0; 2. Use the sizeof() function, which is more used to maintain compatibility with other programming languages; 3. Custom functions, By using a loop to traverse the array, each time it is traversed, the counter is incremented by 1, and finally the length of the array is obtained. Custom functions can be modified and expanded according to actual needs, making them more flexible.

An exploration of performance optimization techniques for PHP arrays An exploration of performance optimization techniques for PHP arrays Mar 13, 2024 pm 03:03 PM

PHP array is a very common data structure that is often used during the development process. However, as the amount of data increases, array performance can become an issue. This article will explore some performance optimization techniques for PHP arrays and provide specific code examples. 1. Use appropriate data structures In PHP, in addition to ordinary arrays, there are some other data structures, such as SplFixedArray, SplDoublyLinkedList, etc., which may perform better than ordinary arrays in certain situations.

What are php array key-value pairs? What are php array key-value pairs? Aug 03, 2023 pm 02:20 PM

PHP array key-value pair is a data structure consisting of a key and a corresponding value. The key is the identifier of the array element, and the value is the data associated with the key. It allows us to store and access data using keys as identifiers. By using key-value pairs, we can more easily operate and manage elements in the array, making program development more flexible and efficient.

What are the functions for averaging arrays in php? What are the functions for averaging arrays in php? Jul 17, 2023 pm 04:03 PM

PHP array averaging functions include: 1. array_sum(), which is used to calculate the sum of all values ​​in the array. In order to calculate the average, you can add all the values ​​in the array and then divide by the number of array elements; 2 , array_reduce(), used to iterate the array and calculate each value with an initial value; 3. array_mean(), used to return the average of the array, first calculate the sum of the array, and calculate the number of array elements, then The sum is divided by the number of array elements to get the average.

See all articles