Trouble Parsing JSON Data with php

huangapple go评论61阅读模式
英文:

Trouble Parsing JSON Data with php

问题

$targetAccountId = "7bf48dba-ef2a-11ed-b8b4-efdca6c6aba7";
foreach ($getdata->accounts as $account) {
    if ($account->id === $targetAccountId) {
        $desiredBalance = $account->availableBalance;
        break;
    }
}
echo $desiredBalance;
英文:

I'm trying to parse json data but im very bad when it comes to json and object oriented programing.

I need to retrieve the availableBalance ONLY from the account with the ID 7bf48dba-ef2a-11ed-b8b4-efdca6c6aba7.

Here is the JSON data in question. I have modified some of the answers to protect sensitive info.

stdClass Object
(
    [accounts] => Array
        (
            [0] => stdClass Object
                (
                    [id] => a706b828-ef59-11ed-772f-8f17da6fccde
                    [accountNumber] => 202343140711
                    [routingNumber] => 091311229
                    [name] => Mercury Checking ••9711
                    [status] => active
                    [type] => mercury
                    [createdAt] => 2023-05-10T11:56:09.165414Z
                    [availableBalance] => 0
                    [currentBalance] => 0
                    [kind] => checking
                    [canReceiveTransactions] => 
                    [nickname] => Martinsville - Noah Parker
                    [legalBusinessName] => Batali Food LLC
                )

            [1] => stdClass Object
                (
                    [id] => 7bf48dba-ef2a-11ed-b8b4-efdca6c6aba7
                    [accountNumber] => 202347437528
                    [routingNumber] => 091311229
                    [name] => Mercury Checking ••7428
                    [status] => active
                    [type] => mercury
                    [createdAt] => 2023-05-10T12:00:46.030313Z
                    [availableBalance] => 0
                    [currentBalance] => 0
                    [kind] => checking
                    [canReceiveTransactions] => 
                    [nickname] => Elkhart - Crystal Sandlin
                    [legalBusinessName] => Batali Food LLC
                )

            [2] => stdClass Object
                (
                    [id] => 9df02094-f1c2-119d-a6e8-c549f8cdb727
                    [accountNumber] => 202393150359
                    [routingNumber] => 091311229
                    [name] => Mercury Checking ••0389
                    [status] => active
                    [type] => mercury
                    [createdAt] => 2023-05-13T19:16:09.399458Z
                    [availableBalance] => 0
                    [currentBalance] => 0
                    [kind] => checking
                    [canReceiveTransactions] => 
                    [nickname] => Incoming - DoorDash ACH
                    [legalBusinessName] => Batali Food LLC
                )

        )

)

and here is my PHP code

<?php
//CONFIGURATION INFO
$apikey = "secret-token:mercury_production_wma_vJjkv3bHNGnv456789GkLtz8qAWaTkhRhvXFoVHRfz_yrucrem";

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://api.mercury.com/api/v1/accounts",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer $apikey",
    "accept: application/json"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
echo "<textarea>";
print_r($response);
}

$getdata = json_decode($response);
?>

I tried several different things but I am very bad at json.

答案1

得分: 1

以下是您要求的翻译内容:

这不是 JSON 数据。这是 JSON 数据的 PHP 版本的 var_dump。json_decode 函数有一个额外的参数,你可以设置为 true,将 JSON 结构转换成一个数组,而不是数组和 PHP 对象的组合。你可能想尝试一下这个选项。

在 PHP 中,你可以使用 $obj->propertyname 来访问对象的公共属性。

json_decode 会将 JSON 对象转换为 PHP 的 stdClass 对象,当需要时,使用包含这些对象的 PHP 数组。你可以通过数字键来识别数组,比如 0、1 等。

所以在这种情况下,你有一个对象,它有一个 accounts 属性,存储着一组账户对象。你想要遍历这个数组,并检查你感兴趣的账户对象属性。

一个更复杂的方法是在 accounts 数组上使用 array_filter() 函数,但在这里,我只展示了如何使用 foreach() 循环。

我还对你展示的对象 id 属性的使用提出了疑问。你能够依赖这个值吗?我认为账号号码(account number)可能是查找你想要的账户更好的方法,因为 guid 值看起来可能会在每个请求中发生变化。

如果我们假设 id 确实始终相同,那么类似这样的代码可能会起作用:

$getdata = json_decode($response);
foreach ($getdata->accounts as $obj) {
    if ($obj->id == '7bf48dba-ef2a-11ed-b8b4-efdca6c6aba7') {
        echo "账户余额:{$obj->availableBalance}";
    }
}

如果你注意到 id 发生变化,请将检查改为 $obj->accountNumber

英文:

That is not the json data. That is a var_dump of the php version of the json data. json_decode, has an extra parameter, you can set to true to transform the json structure into an array, rather than a combination of arrays and php objects. You might want to try that.

In php you can access a public property of an object using $obj->propertyname

json_decode will turn json objects in php stdObjects, using php arrays of those objects when necessary. You can tell the arrays, because they are numerically keyed ... 0, 1 etc.

So in this case you have an object, which has an accounts property, that stores an array of account objects. You want to iterate through that array, and check for the account object property(ies) you are interested in.

A more sophisticated way to do this would be to utilize array_filter() on the accounts array, but here I just show the use of a foreach() loop.

I also question the use of the object id property, you show as being returned. Is that really a value you can depend upon? I'm thinking the accountnumber is probably a better way to find the account you are looking for, as the guid value looks like something that might change with each request.

If we assume, that id is indeed always the same, then something like this will probably work:

$getdata = json_decode($response);
foreach ($getdata->accounts as $obj) {
    if ($obj->id == '7bf48dba-ef2a-11ed-b8b4-efdca6c6aba7') {
        echo "Account balance: {$obj->availableBalance}";
    }
}

Change to check for equivalence to $obj->accountNumber if you notice the id changes.

huangapple
  • 本文由 发表于 2023年5月14日 04:37:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76244777.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定