"data": {
"advance_amount": [],
"collection_report": [
{
"value": 7,
"date": "2018-07-10",
"paid_amount": "3510",
"totalAmount": 4550,
"pending_amount": 990
},
{
"value": 8,
"date": "2018-08-01",
"paid_amount": "1998",
"totalAmount": 7255,
"pending_amount": 3986
},
{
"value": 9,
"date": "2018-09-14",
"paid_amount": "1157",
"totalAmount": 2272,
"pending_amount": 1046
},
{
"advance_amount": "25"
},
{
"advance_amount": null
},
{
"advance_amount": "5225"
}
这是我的回复。但是我想将这些预付金额附加在待处理金额之后的每个collection_report
中。
通过这种方式
"value": 7,
"date": "2018-07-10",
"paid_amount": "3510",
"totalAmount": 4550,
"pending_amount": 990,
"advance_amount": 123,
答案 0 :(得分:1)
$array= json_decode($json);
$array['collection_report'][0]['pending_amount']=25;
$array['collection_report'][1]['pending_amount']=null;
$array['collection_report'][2]['pending_amount']=5225;
这仅供您理解。将json转换回Array,遍历所有项(每个项都是一个数组),在数组中突出显示new key=>value
使用array_key_exists
检查密钥是否存在。
答案 1 :(得分:1)
首先使用json_decode()函数以Array格式获取输出,然后通过简单的for循环即可完成以下任务,从而轻松实现这一目标:
$initialInput = '
{
"advance_amount": [],
"collection_report": [
{
"value": 7,
"date": "2018-07-10",
"paid_amount": "3510",
"totalAmount": 4550,
"pending_amount": 990
},
{
"value": 8,
"date": "2018-08-01",
"paid_amount": "1998",
"totalAmount": 7255,
"pending_amount": 3986
},
{
"value": 9,
"date": "2018-09-14",
"paid_amount": "1157",
"totalAmount": 2272,
"pending_amount": 1046
},
{
"advance_amount": "25"
},
{
"advance_amount": null
},
{
"advance_amount": "5225"
}
]
}
';
代码:
$initialInput = json_decode($initialInput, true);
for($i = 0; $i < count($initialInput['collection_report'])/2;$i++) {
$initialInput['collection_report'][$i]['advance_amount'] = $initialInput['collection_report'][count($initialInput['collection_report'])/2 + $i]['advance_amount'];
}
最终输出:
array:2 [▼
"advance_amount" => []
"collection_report" => array:6 [▼
0 => array:6 [▼
"value" => 7
"date" => "2018-07-10"
"paid_amount" => "3510"
"totalAmount" => 4550
"pending_amount" => 990
"advance_amount" => "25"
]
1 => array:6 [▼
"value" => 8
"date" => "2018-08-01"
"paid_amount" => "1998"
"totalAmount" => 7255
"pending_amount" => 3986
"advance_amount" => null
]
2 => array:6 [▼
"value" => 9
"date" => "2018-09-14"
"paid_amount" => "1157"
"totalAmount" => 2272
"pending_amount" => 1046
"advance_amount" => "5225"
]
3 => array:1 [▼
"advance_amount" => "25"
]
4 => array:1 [▼
"advance_amount" => null
]
5 => array:1 [▼
"advance_amount" => "5225"
]
]
]