Цикл массива массивов для захвата определенного поля - PullRequest
0 голосов
/ 19 сентября 2018

У меня есть данные, которые выглядят примерно так, которые были var_dump отредактированы из данных JSON:

array(50) {
  [0]=>
  array(6) {
    ["id"]=>
    string(25) "zRQaS3CDJxP9smBLsRueV"
    ["location_id"]=>
    string(13) "MB0ERM1RG123"
    ["created_at"]=>
    string(20) "2018-09-18T20:51:52Z"
    ["tenders"]=>
    array(1) {
      [0]=>
      array(9) {
        ["id"]=>
        string(24) "JLMuqRK8xuEsqdvVxzMF"
        ["location_id"]=>
        string(13) "MB0ERMJ123"
        ["transaction_id"]=>
        string(25) "zRQaS3CDJ7r9smBLsRueV"
        ["created_at"]=>
        string(20) "2018-09-18T20:51:39Z"
        ["amount_money"]=>
        array(2) {
          ["amount"]=>
          int(3695)
          ["currency"]=>
          string(3) "USD"
        }
        ["processing_fee_money"]=>
        array(2) {
          ["amount"]=>
          int(102)
          ["currency"]=>
          string(3) "USD"
        }
        ["customer_id"]=>
        string(26) "GZWPPDYF696VH2YHVBQH0W"
        ["type"]=>
        string(4) "CARD"
        ["card_details"]=>
        array(3) {
          ["status"]=>
          string(8) "CAPTURED"
          ["card"]=>
          array(3) {
            ["card_brand"]=>
            string(4) "VISA"
            ["last_4"]=>
            string(4) "2089"
            ["fingerprint"]=>
            string(71) "sq-1-8MESPf1Jq5aDfseysKwy1dQjFc6H96bBGUPLaW3oNcE7PC-s3bbL5-LA"
          }
          ["entry_method"]=>
          string(3) "EMV"
        }
      }
    }
    ["product"]=>
    string(8) "REGISTER"
    ["client_id"]=>
    string(36) "9C90F8EB-00C3-44A7-AC87-0F763CC3B"
  }
  [1]=>
  array(6) {
    ["id"]=>
    string(25) "7VS91iJI4Wt4HoTSsSzznPr"
    ["location_id"]=>
    string(13) "MB0ERM1RGJ123"
    ["created_at"]=>
    string(20) "2018-09-18T20:19:41Z"
    ["tenders"]=>
    array(1) {
      [0]=>
      array(8) {
        ["id"]=>
        string(23) "xEiGixQD2qq9AdoXnLD"
        ["location_id"]=>
        string(13) "MB0ERM1RGJ123"
        ["transaction_id"]=>
        string(25) "7VS91iJI4Wt4HoTSsSzznPr"
        ["created_at"]=>
        string(20) "2018-09-18T20:14:40Z"
        ["amount_money"]=>
        array(2) {
          ["amount"]=>
          int(1700)
          ["currency"]=>
          string(3) "USD"
        }
        ["processing_fee_money"]=>
        array(2) {
          ["amount"]=>
          int(0)
          ["currency"]=>
          string(3) "USD"
        }
        ["type"]=>
        string(4) "CASH"
        ["cash_details"]=>
        array(2) {
          ["buyer_tendered_money"]=>
          array(2) {
            ["amount"]=>
            int(2000)
            ["currency"]=>
            string(3) "USD"
          }
          ["change_back_money"]=>
          array(2) {
            ["amount"]=>
            int(300)
            ["currency"]=>
            string(3) "USD"
          }
        }
      }
    }
    ["product"]=>
    string(8) "REGISTER"
    ["client_id"]=>
    string(36) "F2155BFC-CC49-44D3-9C19-6BA4A3F683"
...

Мне нужно просмотреть эти данные, чтобы получить amount_money => amount.До сих пор я пытался сделать это так:

function enumerateData($data){
    $data = json_decode($data, true);
    foreach($data as $i => $item) {
        echo "<p id='$i-transaction' class='transactions'>Amount spent: ".$item[$i]["tenders"][0]["amount_money"]["amount"]."</p>";
    }
}

Однако, когда я делаю это, я получаю несколько предупреждений:

[Tue Sep 18 16:13:40 2018] PHP Notice:  Undefined index: transactions in /home/tcd/modules/square/connection.php on line 24
[Tue Sep 18 16:13:40 2018] PHP Warning:  Illegal string offset 'cursor' in /home/tcd/modules/square/connection.php on line 24
[Tue Sep 18 16:13:40 2018] PHP Warning:  Illegal string offset 'tenders' in /home/tcd/modules/square/connection.php on line 24
[Tue Sep 18 16:13:40 2018] PHP Warning:  Illegal string offset 'amount_money' in /home/tcd/modules/square/connection.php on line 24
[Tue Sep 18 16:13:40 2018] PHP Warning:  Illegal string offset 'amount' in /home/tcd/modules/square/connection.php on line 24

И это выглядит так:

Amount spent:

Amount spent: C

Что я делаю не так и как я могу извлечь нужные данные из массивов?

Ответы [ 2 ]

0 голосов
/ 19 сентября 2018

Я смог сделать это, просматривая каждый элемент, если это массив:

function enumerateData($data){
    $data = json_decode($data, true);
    foreach($data as $item) {
        if (gettype($item) == "array") {
            foreach ($item as $i => $element){
                $amountSpent = $element["tenders"][0]["amount_money"]["amount"];
                $transactionType = $element["tenders"][0]["type"];
                $processedAt = $element["created_at"];
                echo "<div class='transactions'>";echo "\n";
                echo "    <p id='transaction-{$i}' class='transactions-p-class'>Time created: {$processedAt}<br>Amount spent: {$amountSpent}<br>Transaction type: {$transactionType}</p>";echo "\n";
                echo "</div>";echo "\n";
            }
        }
    }
}
0 голосов
/ 19 сентября 2018

$i - это индекс массива, который вы анализируете, поэтому он не является индексом в массиве, через который вы проходите цикл.Избавление от этого должно решить вашу проблему

function enumerateData($data){
    $data = json_decode($data, true);
    foreach($data as $i => $item) {
        echo "<p id='{$i}-transaction' class='transactions'>Amount spent: ".$item["tenders"][0]["amount_money"]["amount"]."</p>";
    }
}

Отредактировано: добавлены фигурные скобки вокруг переменной $i в строке

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...