在PHP对象中显示键/值

时间:2017-07-17 23:27:50

标签: php

在PHP中,我该如何制作这些数据:

{
   "items": {
     "item": [{
           "id": "59",
           "type": "Domain",
           "relid": "27",
           "description": "Sample Monthly Product(01\ / 01\ / 2016 - 31\ / 01\ / 2016)",
           "amount": "180.00",
           "taxed": "0"
      }]
   }
}

有这种格式:

{
  "items[item][0][id]": "59",
  "items[item][0][type]": "Domain",
  "items[item][0][relid]": "27",
  "items[item][0][description]": "Sample Monthly Product (01\/01\/2016 - 31\/01\/2016)",
  "items[item][0][amount]": "180.00",
  "items[item][0][taxed]": "0"
}

原因:使用电子邮件解析器设置Zap(通过Zapier)从WHMCS导入发票,它似乎与解析第二种格式(items [item] [0] [id])时的数据一起阅读线描述但不是在使用1st时。在WHMCS API ref中它显示它输出为第二种格式,但无法看到为什么我的看起来像1st(developers.whmcs.com/api-reference/getinvoice)

1 个答案:

答案 0 :(得分:0)

我认为这可能适用于您当前的设置:

<?php

//assuming your current dataset isn't in JSON, you can ignore this part
$json = '{
   "items": {
     "item": [{
           "id": "59",
           "type": "Domain",
           "relid": "27",
           "description": "Sample Monthly Product",
           "amount": "180.00",
           "taxed": "0"
      },
      {
           "id": "203",
           "type": "Server",
           "relid": "86",
           "description": "Sample Yearly Product",
           "amount": "290.00",
           "taxed": "1"
      }]
   }
}';

$json = json_decode($json, true);

$parsed = array();

foreach ($json['items']['item'] as $index => $item)
    foreach ($item as $attr => $val)
        $parsed['items[item][' . $index . '][' . $attr . ']'] = $val;

echo json_encode($parsed);

Output

{
    "items[item][0][id]": "59",
    "items[item][0][type]": "Domain",
    "items[item][0][relid]": "27",
    "items[item][0][description]": "Sample Monthly Product",
    "items[item][0][amount]": "180.00",
    "items[item][0][taxed]": "0",
    "items[item][1][id]": "203",
    "items[item][1][type]": "Server",
    "items[item][1][relid]": "86",
    "items[item][1][description]": "Sample Yearly Product",
    "items[item][1][amount]": "290.00",
    "items[item][1][taxed]": "1"
}