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

How to convert array to object in php

王林
王林Original
2021-10-15 16:26:523281browse

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);

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;
}

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!

Statement:
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