使用JSON汇款

时间:2019-02-27 23:21:35

标签: php json

我使用api-transfer-money来处理个人资料页面上的表单。一切正常,突然我的api文件开始向我显示错误“您没有此帐户ID”,我不知道为什么。

clients.json:

{
  "data": {
    "peterjak": {
      "name": "Peter", 
      "accounts": {
        "5c7072a835c3b": {
          "balance": 1000, 
          "name": "Savings"
        }, 
        "5c7696db0745b": {
          "balance": 2000, 
          "name": "University"
        }
      }, 
      "nikajak": {
        "name": "nika", 
        "accounts": {
          "5c7000098525e": {
            "balance": 500
          }
        }
      }
    }
  }
}

api-transfer-money.php:

<?php
session_start();
$sSender = $_SESSION['sUserId'];

$sData = file_get_contents('../data/clients.json');
$jData = json_decode($sData);

$idRecipient = $_POST['txtToAccountId'];
$idSender = $_POST['txtFromAccountId'];

$sBalanceSender = $jData
    ->data
    ->$sSender
    ->accounts->{$idSender}->balance;

if ($sBalanceSender < $iAmount) {
    sendResponse(-1, __LINE__, 'you are too poor');
}
$sSenderAccounts = $jData
    ->data
    ->$sSender->accounts;
$sSenderAccountsList = array_keys($sSenderAccounts);
$sRecipientAccounts = $jData
    ->data
    ->$sRecipient->accounts;
$sRecipientAccountsList = array_keys($sRecipientAccounts);

if (!in_array($idSender, $sSenderAccountsList)) {
    sendResponse(-1, __LINE__, 'You dont have this account id');
}

if (!in_array($idRecipient, $sRecipientAccountsList)) {
    sendResponse(-1, __LINE__, 'Recipients account id not found');
}

$jData
    ->data
    ->$sRecipient
    ->accounts->{$idRecipient}->balance += $iAmount;

// Take money from the logged user
$jData
    ->data
    ->$sSender
    ->accounts->{$idSender}->balance -= $iAmount;

$sData = json_encode($jData);
if ($sData == null) {
    sendResponse(0, __LINE__);
}
file_put_contents('../data/clients.json', $sData);

function sendResponse($iStatus, $iLineNumber, $sMessage) {
    echo '{"status":' . $iStatus . ', "code":' . $iLineNumber . ',"message":"' . $sMessage . '"}';
    exit;
}

1 个答案:

答案 0 :(得分:0)

$sRecipientAccounts$sSenderAccounts是对象,而不是数组,因此您不能使用array_keys()来获取属性名称。

您可以使用get_object_vars()获取属性名称和值的关联数组,然后在其上使用array_keys()。但是只检查指定的属性是否直接存在会更简单。

$sSenderAccounts = $jData->data->$sSender->accounts;
$sRecipientAccounts = $jData->data->$sRecipient->accounts;

if(!isset($sSenderAccounts->{$idSender})){
    sendResponse( -1, __LINE__, 'You dont have this account id'); 
}

if(!isset($sRecipientAccounts->{$idRecipient})){
    sendResponse( -1, __LINE__, 'Recipients account id not found'); 
}