Alright so I'm trying to adjust an array and decode it to json, currently it decodes the array like this;
{"campaignId":"18210f12-502c-4d71-a098-4f595304a8d0","fields.CPLastName":"Voornaam 1","fields.CPFirstname":"Achternaam 1","fields.OROrganisation":"Bedrijf 1"}
{"campaignId":"18210f12-502c-4d71-a098-4f595304a8d0","fields.CPLastName":"Voornaam 2","fields.CPFirstname":"Achternaam 2","fields.OROrganisation":"Bedrijf 2"}
Code:
$request = array();
foreach($address_data as $address) {
foreach($address as $key => $value){
if($key == 'campaignId') {
$request[$key] = $value;
}
if (strpos($key, 'fields') !== false) {
$fields = explode('.', $key);
$request['fields'] = array(
array('fieldId' => $fields[1], 'value' => $value)
);
}
}
echo json_encode($request);
}
What I want to do is, where it says; fields. I want to explode on that and replace fields. with fieldId within a fields array. So something like this;
$request['fields'] = array(array('fieldId' => $key, 'value' => $value));
Now for some reason it will only do the last key, and I want it to loop through all the keys where it says 'fields.'
So the final request should look something like;
{
"campaignId":"18210f12-502c-4d71-a098-4f595304a8d0",
"fields": [
{
"fieldId":"CPLastName",
"value":"Voornaam 1"
},
{
"fieldId": "CPFirstname",
"value": "Achternaam 1"
},
{
"fieldId":"OROrganisation",
"value":"Bedrijf 1"
}
]
}
{
"campaignId":"18210f12-502c-4d71-a098-4f595304a8d0",
"fields": [
{
"fieldId":"CPLastName",
"value":"Voornaam 2"
},
{
"fieldId": "CPFirstname",
"value": "Achternaam 2"
},
{
"fieldId":"OROrganisation",
"value":"Bedrijf 2"
}
]
}
explodeanywhere in what you have currently shown. Please show the actual code of what you have tried, instead of just vaguely and ambiguously describing what you have tried.campaignIdas key on the outermost array level here - but the desired result you have shown does not use any such keys. You would need a normal, continuously numerically indexed array starting with 0 to get that kind of result with json_encode in the first place.$request['fields'] = array(...- this is the issue, you don't increment or add to it, rather overwrite it every time, could do something like;$request['fields'][] = array(...