Pale
Pale

Reputation: 25

How do I put multiple values in an array while foreaching through values in PHP

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"
        }
    ]
}

Upvotes: 1

Views: 63

Answers (1)

04FS
04FS

Reputation: 5820

Use a temporary helper variable in cases like this, that you assemble the array data structure for a single item in.

Add that temp array to the result array at the end of the outer loop.

$request = [];
foreach($address_data as $address) {
    $temp = [];
    foreach($address as $key => $value){
        if($key == 'campaignId') {
            $temp[$key] = $value;
        }
        if (strpos($key, 'fields') !== false) { // === 0 would perhaps make more sense here
            $fields = explode('.', $key);

            $temp['fields'][] = [
                'fieldId' => $fields[1],
                'value' => $value
            ];
        }
    }
   $request[] = $temp;
}

echo json_encode($request);

Upvotes: 1

Related Questions