Home >Backend Development >PHP Tutorial >json - Problem reading stdclass in php?

json - Problem reading stdclass in php?

WBOY
WBOYOriginal
2016-07-06 13:53:241451browse

For example:

<code>array(3) { [0]=> object(stdClass)#6 (2) 
               { ["id"]=> string(1) "1" ["topic_name"]=> string(5) "janus" }
          [1]=> object(stdClass)#7 (2) 
               { ["id"]=> string(2) "10" ["topic_name"]=> string(8) "emulsion" } 
          [2]=> object(stdClass)#33 (2) 
               { ["id"]=> string(2) "14" ["topic_name"]=> string(8) "particle" } }

</code>

What if converted into an array?

Reply content:

For example:

<code>array(3) { [0]=> object(stdClass)#6 (2) 
               { ["id"]=> string(1) "1" ["topic_name"]=> string(5) "janus" }
          [1]=> object(stdClass)#7 (2) 
               { ["id"]=> string(2) "10" ["topic_name"]=> string(8) "emulsion" } 
          [2]=> object(stdClass)#33 (2) 
               { ["id"]=> string(2) "14" ["topic_name"]=> string(8) "particle" } }

</code>

What if converted into an array?

If performance is not strictly required and the encoding is utf-8:

<code class="php">$new_array = json_decode(json_encode($array), true);</code>

If there are strict requirements, we can process it in a loop according to the situation

<code class="php">foreach ($array as $key => $value) {
    $array[$key] = (array)$value;
}</code>

Just use foreach

Thank you for the invitation.
Directly operate through the commonly used -> method of obtaining class attributes. If you need to obtain the transformation of any elements, you can use reflection

<code class="php">$reflection = new ReflectionObject($stdClass);
$properties = $target->getProperties();</code>

ReflectionObject::getProperties

Write a function and use array_map

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