简体   繁体   English

将php API数组收集到json

[英]Harvest php API array to json

Using Harvest php API http://mdbitz.com/harvest-api/examples/ and my harvest php array prints following data: 使用Harvest php API http://mdbitz.com/harvest-api/examples/ ,我的Harvest php数组将打印以下数据:

$myresult = $harvestAPI->getUser($client_id);
$data = $myresult->get( "data" );
print_r($data);

data: 数据:

Harvest_User Object ( [_root:protected] 
=> user [_convert:protected] 
=> 1 [_values:protected] 
=> Array ( [id] 
=> 999 [email] 
=> user@example.com [created-at] 
=> 2014-06-12T20:00:00Z [is-admin] 
=> false [first-name] 
=> John [last-name] 
=> Smith [timezone] 
=> Mountain Time (US & Canada) [is-contractor] 
=> false [telephone] 
=> [is-active] 
=> true [has-access-to-all-future-projects] 
=> false [default-hourly-rate] 
=> 200.0 [department] 
=> Development [dev] 
=> false [updated-at] 
=> 2015-06-15T18:00:00Z [cost-rate] 
=> 100.0 ) )

but when using json class to conver it to json, it gives me empty {} any idea whats happening ? 但是当使用json类将其转换为json时,它让我空{}知道发生了什么事?

$dataJSON = json_encode($data);
print_r($dataJSON);

It does not work because all the properties are protected. 它不起作用,因为所有属性都受到保护。 While print_r is a special debugging function and can display protected properties, json_encode can only read public properties. 虽然print_r是一个特殊的调试功能,并且可以显示受保护的属性,但是json_encode仅可以读取公共属性。 As your Harvest_User object doesn't have any public properties, the JSON object is empty. 由于您的Harvest_User对象没有任何公共属性,因此JSON对象为空。

The Harvest_User class inherits from Harvest_Abstract , which again implements the magic __get and __set methods. Harvest_User类继承自Harvest_Abstract ,后者再次实现了魔术__get__set方法。 Unfortunately, json_encode cannot use them, because it doesn't even know which variables to look for. 不幸的是, json_encode无法使用它们,因为它甚至不知道要寻找哪个变量。

To solve your problem, you can write a helper class to transform your Harvest objects into plain PHP objects and then encode them to JSON. 为了解决您的问题,您可以编写一个帮助程序类,以将Harvest对象转换为纯PHP对象,然后将其编码为JSON。

You might also want to create a bug report for Harvest and ask them to implement Serializable and/or JsonSerializable . 您可能还想为Harvest创建一个错误报告,并要求他们实现Serializable和/或JsonSerializable

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

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