如何将这个 PHP 对象数组转换为 JSON?

3

我有一个包含10个对象的数组,我想要将它们转换成JSON格式。这个数组被存储在一个名为$invoices的变量中。下面是var_dump($invoices)输出的结果,只显示了第一个对象。

我尝试过以下方法:

$invoices = json_encode($invoices, FALSE);
$invoices = json_encode($invoices, TRUE);
$invoices = json_encode($invoices, JSON_UNESCAPED_UNICODE);

然而,输出总是:

string(31) "[{},{},{},{},{},{},{},{},{},{}]"

如何正确将此数组转换为JSON?

注意:我正在运行PHP 5.5.9

更新:

问题是由于json_encode无法处理“受保护的成员变量”。如果我没有访问创建它们的类的权限,有没有一种方法将这些变量声明为公共变量?

array(10) {
  [0]=>
  object(QuickBooks_IPP_Object_Invoice)#285 (1) {
    ["_data":protected]=>
    array(22) {
      ["Id"]=>
      array(1) {
        [0]=>
        string(6) "{-224}"
      }
      ["SyncToken"]=>
      array(1) {
        [0]=>
        string(1) "0"
      }
      ["MetaData"]=>
      array(1) {
        [0]=>
        object(QuickBooks_IPP_Object_MetaData)#282 (1) {
          ["_data":protected]=>
          array(2) {
            ["CreateTime"]=>
            array(1) {
              [0]=>
              string(25) "2014-12-07T09:48:47-08:00"
            }
            ["LastUpdatedTime"]=>
            array(1) {
              [0]=>
              string(25) "2014-12-07T09:48:47-08:00"
            }
          }
        }
      }
      ["CustomField"]=>
      array(1) {
        [0]=>
        object(QuickBooks_IPP_Object_CustomField)#292 (1) {
          ["_data":protected]=>
          array(3) {
            ["DefinitionId"]=>
            array(1) {
              [0]=>
              string(4) "{-1}"
            }
            ["Name"]=>
            array(1) {
              [0]=>
              string(6) "Crew #"
            }
            ["Type"]=>
            array(1) {
              [0]=>
              string(10) "StringType"
            }
          }
        }
      }
      ["DocNumber"]=>
      array(1) {
        [0]=>
        string(4) "1038"
      }
      ["TxnDate"]=>
      array(1) {
        [0]=>
        string(10) "2014-12-07"
      }
      ["Line"]=>
      array(2) {
        [0]=>
        object(QuickBooks_IPP_Object_Line)#263 (1) {
          ["_data":protected]=>
          array(5) {
            ["Id"]=>
            array(1) {
              [0]=>
              string(4) "{-1}"
            }
            ["LineNum"]=>
            array(1) {
              [0]=>
              string(1) "1"
            }
            ["Amount"]=>
            array(1) {
              [0]=>
              string(9) "155555.00"
            }
            ["DetailType"]=>
            array(1) {
              [0]=>
              string(19) "SalesItemLineDetail"
            }
            ["SalesItemLineDetail"]=>
            array(1) {
              [0]=>
              object(QuickBooks_IPP_Object_SalesItemLineDetail)#765 (1) {
                ["_data":protected]=>
                array(2) {
                  ["ItemRef"]=>
                  array(1) {
                    [0]=>
                    string(4) "{-3}"
                  }
                  ["TaxCodeRef"]=>
                  array(1) {
                    [0]=>
                    string(6) "{-NON}"
                  }
                }
              }
            }
          }
        }
        [1]=>
        object(QuickBooks_IPP_Object_Line)#748 (1) {
          ["_data":protected]=>
          array(3) {
            ["Amount"]=>
            array(1) {
              [0]=>
              string(9) "155555.00"
            }
            ["DetailType"]=>
            array(1) {
              [0]=>
              string(18) "SubTotalLineDetail"
            }
            ["SubTotalLineDetail"]=>
            array(1) {
              [0]=>
              string(0) ""
            }
          }
        }
      }
      ["TxnTaxDetail"]=>
      array(1) {
        [0]=>
        object(QuickBooks_IPP_Object_TxnTaxDetail)#287 (1) {
          ["_data":protected]=>
          array(1) {
            ["TotalTax"]=>
            array(1) {
              [0]=>
              string(1) "0"
            }
          }
        }
      }
      ["CustomerRef"]=>
      array(1) {
        [0]=>
        string(5) "{-11}"
      }
      ["BillAddr"]=>
      array(1) {
        [0]=>
        object(QuickBooks_IPP_Object_BillAddr)#284 (1) {
          ["_data":protected]=>
          array(7) {
            ["Id"]=>
            array(1) {
              [0]=>
              string(5) "{-11}"
            }
            ["Line1"]=>
            array(1) {
              [0]=>
              string(13) "1045 Main St."
            }
            ["City"]=>
            array(1) {
              [0]=>
              string(13) "Half Moon Bay"
            }
            ["CountrySubDivisionCode"]=>
            array(1) {
              [0]=>
              string(2) "CA"
            }
            ["PostalCode"]=>
            array(1) {
              [0]=>
              string(5) "94213"
            }
            ["Lat"]=>
            array(1) {
              [0]=>
              string(10) "37.4559621"
            }
            ["Long"]=>
            array(1) {
              [0]=>
              string(11) "-122.429939"
            }
          }
        }
      }
      ["ShipAddr"]=>
      array(1) {
        [0]=>
        object(QuickBooks_IPP_Object_ShipAddr)#814 (1) {
          ["_data":protected]=>
          array(7) {
            ["Id"]=>
            array(1) {
              [0]=>
              string(5) "{-11}"
            }
            ["Line1"]=>
            array(1) {
              [0]=>
              string(13) "1045 Main St."
            }
            ["City"]=>
            array(1) {
              [0]=>
              string(13) "Half Moon Bay"
            }
            ["CountrySubDivisionCode"]=>
            array(1) {
              [0]=>
              string(2) "CA"
            }
            ["PostalCode"]=>
            array(1) {
              [0]=>
              string(5) "94213"
            }
            ["Lat"]=>
            array(1) {
              [0]=>
              string(10) "37.4559621"
            }
            ["Long"]=>
            array(1) {
              [0]=>
              string(11) "-122.429939"
            }
          }
        }
      }
      ["DueDate"]=>
      array(1) {
        [0]=>
        string(10) "2015-01-06"
      }
      ["TotalAmt"]=>
      array(1) {
        [0]=>
        string(9) "155555.00"
      }
      ["ApplyTaxAfterDiscount"]=>
      array(1) {
        [0]=>
        string(5) "false"
      }
      ["PrintStatus"]=>
      array(1) {
        [0]=>
        string(11) "NeedToPrint"
      }
      ["EmailStatus"]=>
      array(1) {
        [0]=>
        string(6) "NotSet"
      }
      ["Balance"]=>
      array(1) {
        [0]=>
        string(9) "155555.00"
      }
      ["Deposit"]=>
      array(1) {
        [0]=>
        string(1) "0"
      }
      ["AllowIPNPayment"]=>
      array(1) {
        [0]=>
        string(5) "false"
      }
      ["AllowOnlinePayment"]=>
      array(1) {
        [0]=>
        string(5) "false"
      }
      ["AllowOnlineCreditCardPayment"]=>
      array(1) {
        [0]=>
        string(5) "false"
      }
      ["AllowOnlineACHPayment"]=>
      array(1) {
        [0]=>
        string(5) "false"
      }
    }
  }
  [1]=>
  object(QuickBooks_IPP_Object_Invoice)#830 (1) {
    ["_data":protected]=>
    array(22) {
    ...
    ...

你应该先说明你正在尝试使用QuickBooks API。Intuit要求您通过OAuth对QuickBooks Online进行身份验证(仅一次)。Intuit要求您注册一个“应用程序”以连接到QuickBooks Online。 - carlodurso
你尝试过使用 $Invoice->getLine(0); 来检查它是否返回任何值了吗? - carlodurso
@Rangad,这对于受保护的成员变量有效吗? - Raphael Rafatpanah
如果这个类没有使用一些奇怪的__get魔法滥用,那么它应该可以。 - Rangad
@Rangad,谢谢。我会去看看的。 - Raphael Rafatpanah
显示剩余3条评论
4个回答

2

最好的方法是实现JsonSerializable类并定义jsonSerialize()函数。

示例:

class MyObj implements JsonSerializable{
    protected $id;
    protected $name;

    function getId() { return $this->$id; }
    function getName() { return $this->$name; }
  
     public function jsonSerialize() {
                return [
                'Id' => $this->getId(),
                'Name' => $this->getName()
            ];
        }
}

// $arrofobj is array of objects of type MyObj 
json_encode($arrofobj);  //this will convert array of objects to JSON

1
如果这些类无法实现JsonSerializable,您可以使用Reflection访问受保护的属性。
例子:
class Publisher {
    protected $name;
    protected $id;
    public function __construct($id, $name) {
        $this->id = $id;
        $this->name = $name;
    }
}

function getPublisherExportData($publishers) {
    $out = [];
    foreach($publishers as $publisher) {
        $currentPData = [];
        $refl = new ReflectionClass($publisher);
        $props = $refl->getProperties(ReflectionProperty::IS_PROTECTED);
        foreach($props as $prop) {
            $prop->setAccessible(true);
            $currentPData[$prop->getName()] = $prop->getValue($publisher);
        }
        $out[] = $currentPData;
    }

    return $out;
}

var_dump(json_encode(getPublisherExportData([new Publisher(12, 'My Name'), new Publisher(15, 'NameProperty')]), JSON_PRETTY_PRINT));

会产生以下结果:
string(121) "[ { "name": "My Name", "id": 12 }, { "name": "NameProperty", "id": 15 } ]"

然而,您需要自己处理对象图和条件导出。根据所需的JSON输出,您可以考虑使用stdClass实例替换$out,并使用$out->{$prop->getName()} = $val语法编写。如果您能够使用自定义实现,则可以添加一个使用get_object_vars($this)的方法来避免上面大部分的代码,但是如果您能够这样做,应该考虑实现JsonSerializable,它就是为此任务而设计的。

0
你需要为你的类"QuickBooks_IPP_Object_MetaData"编写一个函数并获取一个数组。你可能会看到这个问题,将PHP对象序列化为JSON

我认为这可能是我的答案。让我试着让它工作,如果我能解决我的问题,我会将您的答案标记为正确。谢谢。 - Raphael Rafatpanah

0
最终,这是我选择使用的解决方案:
function objectToArray ($object) {
    if(!is_object($object) && !is_array($object))
        return $object;

    return array_map('objectToArray', (array) $object);
}

从这里开始:如何将对象转换为数组?

对于多维数组(而不是包含受保护变量的对象数组),json_encode()非常有效。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接