Home > Backend Development > PHP Problem > How to convert array to object in php

How to convert array to object in php

王林
Release: 2023-03-13 10:36:01
Original
3285 people have browsed it

php method to convert array to object: [$array=array('xxx'=>'xxx'); $vl=json_encode($array); $ob=json_decode($vl); print_r ($ob);].

How to convert array to object in php

The operating environment of this article: windows10 system, php 7, thinkpad t480 computer.

Conversion between array and object:

1. Convert array to Object

$array=array('a' =>'哈哈','b' =>'bnbbbb','西' =>'嘻嘻嘻');
$vl=json_encode($array);
$ob=json_decode($vl);
 echo "<pre class="brush:php;toolbar:false">";
 print_r($ob);
Copy after login

2. Convert Object to array

在Object变量前加 (array)
示例1:
	$data=(array)$Object;
	var_dump($data);


示例2:
//或者调用这个函数,将其幻化为数组,然后取出对应值
function object_array($array)
{
   if(is_object($array))
   {
    $array = (array)$array;
   }
   if(is_array($array))
   {
    foreach($array as $key=>$value)
    {
     $array[$key] = object_array($value);
    }
   }
   return $array;
}
Copy after login

Recommended learning: php Training

The above is the detailed content of How to convert array to object in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template