在PHP对象中显示键/值
在PHP中,如何生成以下数据:在PHP对象中显示键/值,php,Php,在PHP中,如何生成以下数据: { "items": { "item": [{ "id": "59", "type": "Domain", "relid": "27", "description": "Sample Monthly Product(01\ / 01\ / 2016 - 31\ / 01\ / 2016)", "amount": "180.00",
{
"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)从WHMC导入发票,当第二种格式(items[item][0][id])读取行描述时,它似乎可以解析数据,但在使用第一种格式时却不能。在WHMCS API ref中,它显示输出为第二种格式,但不明白为什么我的格式看起来像第一种格式(developers.WHMCS.com/API reference/getinvoice)我认为这可能适用于您当前的设置:
<?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);
是否确实希望您的密钥为:
“items[item][0][id]”
?那只是。。。奇怪,你为什么要这么做。这几乎已经是你想要的了欢迎来到StackOverflow!首先,您有一个对象
,而不是数组
。其次,您的对象充满了语法错误。你能保证这些信息是正确的吗?第三,你为什么要这样重组?您的数据已采用高度可访问的格式。您正在尝试附加一个[0]
索引吗?假设您在循环中运行此操作,您只需使用foreach
。使用电子邮件解析器设置Zap(通过Zapier)从WHMC导入发票,它似乎可以使用第二种格式(items[item][0][id])来读取行说明,但在使用第一种格式时则不行。在WHMCS API ref中,它显示输出为第二种格式,但如果向下滚动到,则看不出为什么我的格式看起来像第1种(),您可以看到API所期望的内容。转换只需要两个for循环来展平阵列。
{
"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"
}