簡體   English   中英

將多維對象轉換為數組

[英]Convert multidimensional objects to array

我正在使用亞馬遜產品廣告 api。 值作為多維對象返回。

它看起來像這樣:

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

我的意思是它在對象內部也有數組。 我想將它們全部轉換為多維數組。

我知道這很舊,但您可以嘗試以下代碼:

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

其中 $object 是 API 的響應。

您可以使用如下遞歸函數:

function object_to_array($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;
}
function convertObjectToArray($data) {
    if (is_object($data)) {
        $data = get_object_vars($data);
    }

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

    return $data;
}

感謝 Kevin Op den Kamp。

我編寫了一個函數來完成這項工作,並將所有 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;
}

這是一個老問題,但我最近遇到了這個問題並提出了我自己的解決方案。

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

現在,如果$array本身是一個對象,您可以在將其放入array_walk_recursive之前將其轉換為數組:

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

和小例子:

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

在我的情況下,我有一個來自 3rd 方源的 stdClass 對象數組,該對象有一個字段/屬性,我需要將其值用作查找其包含的 stdClass 的引用,以便我可以訪問該元素中的其他數據。 基本上比較 2 個數據集中的嵌套鍵。

我必須多次這樣做,所以我不想為我需要找到的每個項目都遍歷它。 該問題的解決方案通常是array_column ,但這不適用於對象。 所以我先做了上面的。

以防萬一你像我一樣來到這里並且沒有找到適合你情況的正確答案,這個先前答案之一的修改版本最終對我有用:

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM