php 将多维对象转换为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13567939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:41:50  来源:igfitidea点击:

Convert multidimensional objects to array

phparraysmultidimensional-array

提问by Giri

I'm using amazon product advertising api. Values are returned as a multidimensional objects.

我正在使用亚马逊产品广告 api。值作为多维对象返回。

It looks like this:

它看起来像这样:

object(AmazonProduct_Result)#222 (5) {
  ["_code":protected]=>
  int(200)
  ["_data":protected]=>
  string(16538) 
array(2) {
    ["IsValid"]=>
    string(4) "True"
    ["Items"]=>
    array(1) {
      [0]=>
      object(AmazonProduct_Item)#19 (1) {
        ["_values":protected]=>
        array(11) {
          ["ASIN"]=>
          string(10) "B005HNF01O"
          ["ParentASIN"]=>
          string(10) "B008RKEIZ8"
          ["DetailPageURL"]=>
          string(120) "http://www.amazon.com/Case-Logic-TBC-302-FFP-Compact/dp/B005HNF01O?SubscriptionId=AKIAJNFRQCIJLTY6LDTA&tag=*********-20"
          ["ItemLinks"]=>
          array(7) {
            [0]=>
            object(AmazonProduct_ItemLink)#18 (1) {
              ["_values":protected]=>
              array(2) {
                ["Description"]=>
                string(17) "Technical Details"
                ["URL"]=>
                string(217) "http://www.amazon.com/Case-Logic-TBC-302-FFP-Compact/dp/tech-data/B005HNF01O%3FSubscriptionId%3DAKIAJNFRQCIJLTY6LDTA%26tag%*******-20%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB005HNF01O"
              }
            }
            [1]=>
            object(AmazonProduct_ItemLink)#17 (1) {
              ["_values":protected]=>
              array(2) {

I mean it also has array inside objects. I would like to convert all of them into a multidimensional array.

我的意思是它在对象内部也有数组。我想将它们全部转换为多维数组。

回答by kendepelchin

I know this is old but you could try the following piece of code:

我知道这很旧,但您可以尝试以下代码:

$array = json_decode(json_encode($object), true);

$array = json_decode(json_encode($object), true);

where $object is the response of the API.

其中 $object 是 API 的响应。

回答by SubRed

You can use recursive function like below:

您可以使用如下递归函数:

function objToArray($obj, &$arr){

    if(!is_object($obj) && !is_array($obj)){
        $arr = $obj;
        return $arr;
    }

    foreach ($obj as $key => $value)
    {
        if (!empty($value))
        {
            $arr[$key] = array();
            objToArray($value, $arr[$key]);
        }
        else
        {
            $arr[$key] = $value;
        }
    }
    return $arr;
}

回答by Quolonel Questions

function convertObjectToArray($data) {
    if (is_object($data)) {
        $data = get_object_vars($data);
    }

    if (is_array($data)) {
        return array_map(__FUNCTION__, $data);
    }

    return $data;
}

Credit to Kevin Op den Kamp.

感谢 Kevin Op den Kamp。

回答by Amin Adel

I wrote a function that does the job, and also converts all json strings to arrays too. This works pretty fine for me.

我编写了一个函数来完成这项工作,并将所有 json 字符串也转换为数组。这对我来说很好用。

function is_json($string) {
    // php 5.3 or newer needed;
    json_decode($string);
    return (json_last_error() == JSON_ERROR_NONE);
}

function objectToArray($objectOrArray) {
    // if is_json -> decode :
    if (is_string($objectOrArray)  &&  is_json($objectOrArray)) $objectOrArray = json_decode($objectOrArray);

    // if object -> convert to array :
    if (is_object($objectOrArray)) $objectOrArray = (array) $objectOrArray;

    // if not array -> just return it (probably string or number) :
    if (!is_array($objectOrArray)) return $objectOrArray;

    // if empty array -> return [] :
    if (count($objectOrArray) == 0) return [];

    // repeat tasks for each item :
    $output = [];
    foreach ($objectOrArray as $key => $o_a) {
        $output[$key] = objectToArray($o_a);
    }
    return $output;
}

回答by ArtisticPhoenix

This is an old question, but I recently ran into this and came up with my own solution.

这是一个老问题,但我最近遇到了这个问题并提出了我自己的解决方案。

array_walk_recursive($array, function(&$item){
    if(is_object($item)) $item = (array)$item;
});

Now if $arrayis an object itself you can just cast it to an array before putting it in array_walk_recursive:

现在,如果$array是一个对象本身,您可以在将其放入之前将其转换为数组array_walk_recursive

$array = (array)$object;
array_walk_recursive($array, function(&$item){
    if(is_object($item)) $item = (array)$item;
});

And the mini-example:

和小例子:

array_walk_recursive($array,function(&$item){if(is_object($item))$item=(array)$item;});

In my case I had an array of stdClass objects from a 3rd party source that had a field/property who's value I need to use as a reference to find it's containing stdClass so I can access other data in that element. Basically comparing nested keys in 2 data sets.

在我的情况下,我有一个来自 3rd 方源的 stdClass 对象数组,该对象有一个字段/属性,我需要将其值用作引用以查找它包含 stdClass,以便我可以访问该元素中的其他数据。基本上比较 2 个数据集中的嵌套键。

I have to do this many times, so I didn't want to foreach over it for each item I need to find. The solution to that issue is usually array_column, but that doesn't work on objects. So I did the above first.

我必须多次这样做,所以我不想为我需要找到的每个项目都遍历它。该问题的解决方案通常是array_column,但这不适用于对象。所以我先做了上面的。

Cheers!

干杯!

回答by Ixalmida

Just in case you came here as I did and didn't find the right answer for your situation, this modified version of one of the previous answers is what ended up working for me:

以防万一你像我一样来到这里并且没有找到适合你情况的正确答案,这个先前答案之一的修改版本最终对我有用:

protected function objToArray($obj)
{
    // Not an object or array
    if (!is_object($obj) && !is_array($obj)) {
        return $obj;
    }

    // Parse array
    foreach ($obj as $key => $value) {
        $arr[$key] = $this->objToArray($value);
    }

    // Return parsed array
    return $arr;
}

The original value is a JSON string. The method call looks like this:

原始值是一个 JSON 字符串。方法调用如下所示:

$array = $this->objToArray(json_decode($json, true));