首页 > 解决方案 > PHP array get values

问题描述

N00B here, I have the following php array output, and for the life of me I cannot extract the array values - I have looped through the array and tried to output $array['AmountPaid']. I have noticed in other postings the array has a => rather than : to separate the key from the values and then this is used: $array=>AmountPaid

{
  "Type": "ACCREC",
  "Contact": {
    "ContactID": "37918a06-92f6-4edb-bfe0-1fc041c90f8b",
    "Name": "Boom FM",
    "ContactPersons": [],
    "Addresses": [],
    "Phones": [],
    "ContactGroups": [],
    "HasAttachments": false,
    "HasValidationErrors": false
  },
  "LineItems": [],
  "Date": "2020-04-08",
  "DueDate": "2020-04-21",
  "LineAmountTypes": "Exclusive",
  "InvoiceNumber": "INV-0010",
  "Reference": "Training",
  "CurrencyCode": "USD",
  "Status": "PAID",
  "SubTotal": 500,
  "TotalTax": 41.25,
  "Total": 541.25,
  "InvoiceID": "4c4db294-3633-45cd-8706-f0b3b0079609",
  "HasAttachments": false,
  "IsDiscounted": false,
  "Payments": [],
  "Prepayments": [],
  "Overpayments": [],
  "AmountDue": 0,
  "AmountPaid": 0,
  "FullyPaidOnDate": "2020-04-19",
  "AmountCredited": 541.25,
  "UpdatedDateUTC": "2008-12-20T18:38:32+01:00",
  "CreditNotes": [
    {
      "Date": "2020-04-19",
      "LineItems": [],
      "Total": 541.25,
      "CreditNoteID": "602f5486-664e-492f-b4d1-e12df1d4b8ba",
      "CreditNoteNumber": "CN-0014",
      "AppliedAmount": 541.25,
      "HasAttachments": false,
      "HasErrors": false
    }
  ],
  "HasErrors": false
}

标签: phparrays

解决方案


这是一个 JSON 字符串,而不是 PHP 数组。要转换,您可以这样做:

    $string = '{ "Type": "ACCREC", "Contact": { "ContactID": "37918a06-92f6-4edb-bfe0-1fc041c90f8b", "Name": "Boom FM", "ContactPersons": [], "Addresses": [], "Phones": [], "ContactGroups": [], "HasAttachments": false, "HasValidationErrors": false }, "LineItems": [], "Date": "2020-04-08", "DueDate": "2020-04-21", "LineAmountTypes": "Exclusive", "InvoiceNumber": "INV-0010", "Reference": "Training", "CurrencyCode": "USD", "Status": "PAID", "SubTotal": 500, "TotalTax": 41.25, "Total": 541.25, "InvoiceID": "4c4db294-3633-45cd-8706-f0b3b0079609", "HasAttachments": false, "IsDiscounted": false, "Payments": [], "Prepayments": [], "Overpayments": [], "AmountDue": 0, "AmountPaid": 0, "FullyPaidOnDate": "2020-04-19", "AmountCredited": 541.25, "UpdatedDateUTC": "2008-12-20T18:38:32+01:00", "CreditNotes": [ { "Date": "2020-04-19", "LineItems": [], "Total": 541.25, "CreditNoteID": "602f5486-664e-492f-b4d1-e12df1d4b8ba", "CreditNoteNumber": "CN-0014", "AppliedAmount": 541.25, "HasAttachments": false, "HasErrors": false } ], "HasErrors": false }'

    $data = json_decode($string, true); //Second parameter forces conversion to array

    var_dump($data);

推荐阅读