简体   繁体   English

将所有json解码对象转换为php中的数组

[英]convert all json decoded objects to array in php

I have a JSON decoded object(see the picture): 我有一个JSON解码对象(见图):

从浏览器打印屏幕

I want to convert whole object to array(also children object). 我想将整个对象转换为数组(也是子对象)。 When I do something like this 当我做这样的事情

$parent_object = (array)$parent_object;

It converts only parent object, children objects are still objects. 它只转换父对象,子对象仍然是对象。 Is there way to convert all objects to array at once, instead of using (array) every time? 有没有办法一次将所有对象转换为数组,而不是每次都使用(数组)?

Does the solution from here help? 这里的解决方案有帮助吗?

function object_to_array($obj) {
    if(is_object($obj)) $obj = (array) $obj;
    if(is_array($obj)) {
        $new = array();
        foreach($obj as $key => $val) {
            $new[$key] = object_to_array($val);
        }
    }
    else $new = $obj;
    return $new;       
}

This function recursively creates a new array which contains anything except objects 此函数以递归方式创建一个包含除对象之外的任何内容的新数组

For a complex object, I was getting null chars within the array keys stemming from the simplification of the object when type-casted as (array). 对于一个复杂的对象,当类型转换为(数组)时,我在数组键中获得了空字符,这些字符来源于对象的简化。

When var_dumped , a(str) array key would look like this: var_dumped ,(str)数组键看起来像这样:

arrayKey (str 9 chars, with the null char hidden within) the actual string: array(NULL CHAR)Key arrayKey (str 9 chars,其中隐藏了null char)实际的字符串:array(NULL CHAR)Key

The best way to deal with it is to further clean the keys by removing null chars (char 0). 处理它的最好方法是通过删除空字符(char 0)来进一步清理键。

This adaptation works: 这种改编有效:

function objectToArray($obj) {
    if(is_object($obj)) {
        $obj = (array) $obj;
        $aobj = array();
        foreach ($obj as $key=>$value) {
            $aobj[_cleanStr($key)] = $value; //sanitize the str for null chars
        }
        $obj = $aobj;
    }
    if(is_array($obj)) {
        $new = array();
        foreach($obj as $key => $val) {
            $new[_cleanStr($key)] = objectToArray($val);
        }
    }
    else $new = $obj;

    return $new;
}

//Clean string
function _cleanStr($str) {
    $str = str_replace("", "", $str); //remove null chars
    return $str;
}

最好为json_decode()函数设置第二个参数TRUE当为TRUE ,返回的objects将被转换为关联arrays )像这样 -

json_decode($json, TRUE);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM