将 Json 解析为 php 表会导致未定义索引

Parsing Json into php table results in Undefined index

提问人:Blazion 提问时间:5/12/2018 最后编辑:NahBlazion 更新时间:5/12/2018 访问量:454

问:

我正在访问“ConnectWise”的 API。数据采用 JSON 格式。我能够通过PHP将数据解析为表格。但是,JSON 中的空字段会导致未定义的索引。例如,对于某些没有网站或地址的项目,会发生这种情况。其余的都显示得很好。 任何帮助或意见将不胜感激。

这是我从 Connectwise 获取数据的代码:

function get_companies(){

   $curl = curl_init();
   curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1);
   curl_setopt($curl, CURLOPT_URL, "https://api- 
   na.myconnectwise.net/v4_6_release/apis/3.0/company/companies");
   curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 );
   curl_setopt($curl, CURLOPT_HTTPHEADER, array(

  "Authorization: Basic (OUR KEY)",

   'Content-type: application/json'

       ));

$result = curl_exec($curl);
curl_close($curl);
$decoded =  json_decode($result,true);
return $decoded;
}

并显示数据:

function list_all_accounts(){

    $accounts = get_companies();

    if ( !empty ($accounts)){
            foreach ($accounts as $account) {

                {
        echo "
                    </td>
                    <td>
                        $account[id]
                    </td>
                    <td>
                        $account[name]
                    </td>
                    <td>
                        $account[addressLine1]
                    </td>
                    <td>
                         $account[phoneNumber]
                    </td>
                    <td>
                         $account[website]
                    </td>   
                    <td>
                        $account[name]
                    </td>                       
                    </tr>";
            }
    }
   }
 }

更新 - Json 示例

    [
    {
        "id": 250,
        "identifier": "company name ",
        "name": "company name",
        "status": {
            "id": 1,
            "name": "Active",
            "_info": {
                "status_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/statuses/1"
            }
        },
        "type": {
            "id": 1,
            "name": "Client",
            "_info": {
                "type_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/types/1"
            }
        },
        "addressLine1": "address line 1",
        "city": "New York",
        "state": "NY",
        "zip": "11111",
        "country": {
            "id": 1,
            "name": "United States",
            "_info": {
                "country_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/countries/1"
            }
        },
        "phoneNumber": "123456789",
        "faxNumber": "",
        "website": "www.site.com",
        "territoryId": 2,
        "accountNumber": "",
        "dateAcquired": "2006-06-21T04:00:00Z",
        "sicCode": {
            "id": 1209,
            "name": "consulting"
        },
        "annualRevenue": 0,
        "timeZone": {
            "id": 1,
            "name": "GMT-5/Eastern Time: US & Canada",
            "_info": {
                "timeZoneSetup_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/system/timeZoneSetups/1"
            }
        },
        "leadFlag": false,
        "unsubscribeFlag": false,
        "userDefinedField5": "1",
        "taxCode": {
            "id": 8,
            "name": "Tax-State",
            "_info": {
                "taxCode_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/taxCodes/8"
            }
        },
        "billingTerms": {
            "id": 1,
            "name": "Net 30 days"
        },
        "billToCompany": {
            "id": 250,
            "identifier": "comp1 ",
            "name": "company1.",
            "_info": {
                "company_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/250"
            }
        },
        "billingSite": {
            "id": 1291,
            "name": "company1",
            "_info": {
                "site_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies"
            }
        },
        "invoiceDeliveryMethod": {
            "id": 1,
            "name": "Mail"
        },
        "deletedFlag": false,
        "mobileGuid": "1df91371-6d7a-4778-ab81-f3e7761f5211",
        "currency": {
            "id": 7,
            "symbol": "$",
            "isoCode": "USD",
            "name": "US Dollars",
            "_info": {
                "currency_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/currencies/7"
            }
        },
        "_info": {
            "lastUpdated": "2018-04-02T16:36:05Z",
            "updatedBy": "user1",
            "dateEntered": "2006-06-21T16:04:59Z",
        }
    },
     {
        "id": 250,
        "identifier": "company name ",
        "name": "company name",
        "status": {
            "id": 1,
            "name": "Active",
            "_info": {
                "status_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/statuses/1"
            }
        },
        "type": {
            "id": 1,
            "name": "Client",
            "_info": {
                "type_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/types/1"
            }
        },
        "addressLine1": "address line 1",
        "city": "New York",
        "state": "NY",
        "zip": "11111",
        "country": {
            "id": 1,
            "name": "United States",
            "_info": {
                "country_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/countries/1"
            }
        },
        "phoneNumber": "123456789",
        "faxNumber": "",
        "website": "www.site.com",
        "territoryId": 2,
        "accountNumber": "",
        "dateAcquired": "2006-06-21T04:00:00Z",
        "sicCode": {
            "id": 1209,
            "name": "consulting"
        },
        "annualRevenue": 0,
        "timeZone": {
            "id": 1,
            "name": "GMT-5/Eastern Time: US & Canada",
            "_info": {
                "timeZoneSetup_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/system/timeZoneSetups/1"
            }
        },
        "leadFlag": false,
        "unsubscribeFlag": false,
        "userDefinedField5": "1",
        "taxCode": {
            "id": 8,
            "name": "Tax-State",
            "_info": {
                "taxCode_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/taxCodes/8"
            }
        },
        "billingTerms": {
            "id": 1,
            "name": "Net 30 days"
        },
        "billToCompany": {
            "id": 250,
            "identifier": "comp1 ",
            "name": "company1.",
            "_info": {
                "company_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies/250"
            }
        },
        "billingSite": {
            "id": 1291,
            "name": "company1",
            "_info": {
                "site_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/company/companies"
            }
        },
        "invoiceDeliveryMethod": {
            "id": 1,
            "name": "Mail"
        },
        "deletedFlag": false,
        "mobileGuid": "1df91dd371-6d7addd-4778s-ab81-f3e7761f5211",
        "currency": {
            "id": 7,
            "symbol": "$",
            "isoCode": "USD",
            "name": "US Dollars",
            "_info": {
                "currency_href": "https://api-na.myconnectwise.net/v4_6_release/apis/3.0/finance/currencies/7"
            }
        },
        "_info": {
            "lastUpdated": "2018-04-02T16:36:05Z",
            "updatedBy": "user1",
            "dateEntered": "2006-06-21T16:04:59Z",
            "enteredBy": "CONVERSION",
        }
    }
]
php json 未定义索引 jsonobjectrequest

评论

0赞 Nick 5/12/2018
一些导致错误的示例 JSON 数据会有所帮助......
1赞 Spoody 5/12/2018
PHP 的可能重复:“注意:未定义的变量”、“注意:未定义的索引”和“注意:未定义的偏移量”
0赞 Blazion 5/12/2018
使用示例 JSON 进行了更新
0赞 Greg Schmidt 5/12/2018
这个确切的 JSON 是否会导致错误?看起来您引用的所有键都存在于这里的两条记录中,因此,如果此输入导致这些错误,那么您的主要问题似乎出在其他地方。(并不是说你的代码没有问题......
0赞 Blazion 5/12/2018
@GregSchmidt - 是的,同一个,至少前 2 个。例如,如果其中一个字段“网站”为空,则会发生错误。它显示 “Website”: “”,

答:

0赞 ivanivan 5/12/2018 #1

json_decode()和 https://jsonlint.com/ 都抱怨第 95 行和第 194 行的值后面的逗号。删除它们会使它成为有效的 json,之后只要你记得引用关联数组的键值,你的代码就会工作。

我删除了 json 中的两个有问题的逗号并另存为文件,然后在数组上添加了键值的引用,最后删除了 HTML 表格等内容(我只是在命令行上运行它以查看输出)。应该很容易放回去......

<?php

function get_companies() {
    $j = file_get_contents("json.json");
    $jd = json_decode($j, true);
    return $jd;
}

$accounts = get_companies();
if (!empty($accounts)) {
    foreach ($accounts as $account) {
        echo  "\n".$account['id'] . "
              " . $account['name'] . "
              " . $account['addressLine1'] . "
              " . $account['phoneNumber'] . "
              " . $account['website'] . "
              " . $account['name']."\n\n";
    }
}
?>

评论

1赞 Greg Schmidt 5/12/2018
可以肯定的是,JSON 合规性不是 OP 的问题。
0赞 Blazion 5/13/2018
JSON格式不是问题。正如我上面提到的,它是 JSON 的修改版本,用于删除我们客户的数据。我为错别字道歉。
0赞 Namoshek 5/12/2018 #2

根据您的评论,您在 HTML 中使用的某些属性可能不是您收到的 JSON 的一部分。这意味着您正在访问未设置的数组索引,例如使用 .$account[website]

我看到了两种解决方案:

  1. 仅当在数组中设置数据时才输出数据:

    echo '<td>'.(isset($account['website']) ? $account['website'] : '').'</td>';
    
  2. 使用一个具有所有值默认值的数组作为数组的基础,并将它们合并:$account

    $base = [
        'website' => 'no website',
        'phoneNumber' => '',
    ];
    
    foreach ($accounts as $account) {
        // this will override all elements of $base with them of $account,
        // but only if they are present in $account
        $account = array_merge($base, $account);
    
        // ... your output here ...
    }
    

评论

0赞 Blazion 5/13/2018
谢谢,但$account[网站]显示了具有可用属性的项目。如果该属性为空,则会导致问题。