如何从类中获取数据并在JSON中转换结果

时间:2019-07-17 07:45:42

标签: php laravel

我创建了一个类“ ZohoV2”。

此类包含一个从CRM模块中检索数据的函数。

public function getUsers(){
    $bulkAPIResponse=ZCRMOrganization::getInstance()->getAllUsers();
    $users=$bulkAPIResponse->getData();
}

当我执行print_r($users)时,该函数返回结果。

Array
(
    [0] => zcrmsdk\crm\crud\ZCRMRecord Object
        (
            [entityId:zcrmsdk\crm\crud\ZCRMRecord:private] => 2076424000000355008
            [moduleApiName:zcrmsdk\crm\crud\ZCRMRecord:private] => Leads
            [lineItems:zcrmsdk\crm\crud\ZCRMRecord:private] => Array
                (
                )

            [lookupLabel:zcrmsdk\crm\crud\ZCRMRecord:private] => 
            [owner:zcrmsdk\crm\crud\ZCRMRecord:private] => zcrmsdk\crm\setup\users\ZCRMUser Object
                (
                    [id:zcrmsdk\crm\setup\users\ZCRMUser:private] => 2076424000000104007
                    [name:zcrmsdk\crm\setup\users\ZCRMUser:private] => A-th Admin
                    [signature:zcrmsdk\crm\setup\users\ZCRMUser:private] => 
                    [country:zcrmsdk\crm\setup\users\ZCRMUser:private] => 
                    [role:zcrmsdk\crm\setup\users\ZCRMUser:private] => 
                    [customizeInfo:zcrmsdk\crm\setup\users\ZCRMUser:private] => 
                    [city:zcrmsdk\crm\setup\users\ZCRMUser:private] => 
                    [nameFormat:zcrmsdk\crm\setup\users\ZCRMUser:private] => 
                    [language:zcrmsdk\crm\setup\users\ZCRMUser:private] => 
                    [locale:zcrmsdk\crm\setup\users\ZCRMUser:private] => 
                    [isPersonalAccount:zcrmsdk\crm\setup\users\ZCRMUser:private] => 
                    …

documentation请求添加此功能以循环显示数据

foreach($users as $userInstance)
          {
          echo $userInstance->getCountry();
          $roleInstance=$userInstance->getRole();
          echo $roleInstance->getId();
          echo $roleInstance->getName();
          …

它有效,并且返回以下结果

2076424000000026008Employefr_FRfr_FRUSConsultantf.jerom@ith.comHH:mm2076424000000538017ConsultantIthEurope/London6372345901Ith Consultantdd/MM/yyyyactive2076424000000026005CEO1Salutation,Last Name,First Namefr_FRfr_FR0#FFFFFF#222222#FFFFFF#222222FRAdmininfo@Ith.comfr_BEHH:mm2076424000000026011Administrator0491078106A-thCET6334039531Ith Admin0491078106dd/MM/yyyyactive

我有一个函数results(),我在控制器中调用它来显示数据。

public function results()
{
    $obj = new ZohoV2();
    $obj->getUsers();

}

我不知道如何利用这些数据。这是我第一次使用API​​。

例如,如何将结果转换为JSON?有这样的结果吗? (documentation将其显示为预期的结果,但我及其代码中有上面显示的表格)

{
"users": [
   {
        "country": null,
        "role": {
            "name": "CEO",
            "id": "2445013000000026005"
        },
        "city": null,
        "signature": null,

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

使用序列化:https://laravel.com/docs/5.8/eloquent-serialization

$user = App\User::find(1);

return $user->toJson();

return $user->toJson(JSON_PRETTY_PRINT);