hi all,

I am trying to make an array that looks like this:

Array
(
    [status] => 
    [MERGE0] => removed@email.address
    [merge_fields] => Array
        (
            [MERGE1] => James
            [MERGE2] => doe
        )

)

In my code, there is an undefined number of [merge_fields], so I am using the code below to try create an array in the above format:

$i = 0;
foreach($data as $d):
$mergeField[] = ['MERGE'.$i.'' => $d];
$i++;
endforeach;

    $json2 = [
    'status'        => $status,
        'MERGE0' => $data['email'],
        'merge_fields'  => $mergeField
    ];

However, this outputs this:

Array
(
    [status] => 
    [MERGE0] => removed@email.address
    [merge_fields] => Array
        (
            [0] => Array
                (
                    [MERGE0] => removed@email.address
                )

            [1] => Array
                (
                    [MERGE1] => James
                )

            [2] => Array
                (
                    [MERGE2] => doe
                )

            [3] => Array
                (
                    [MERGE3] => Masterton
                )

        )

)

Basically, I need to get rid of the parent keys for each merge item... How do I go about this??

Recommended Answers

All 3 Replies

Member Avatar for diafol
$data = ['email'=>'blah@gmail.com','firstname'=>'Alun', 'surname'=>'Llewelyn', 'location'=>'Abertawe'];
$status = 1;

$array = [];
$merge = [];
$array['status'] = $status;
$array['MERGE0'] = $data['email'];
unset($data['email']);
$reData = array_values($data);
for($i=0;$i<count($reData);$i++)
    $merge['MERGE' . ($i+1)] = $reData[$i];
$array['mergefields'] = $merge;

echo "<pre>";
print_r($array);

gives...

Array
(
    [status] => 1
    [MERGE0] => blah@gmail.com
    [mergefields] => Array
        (
            [MERGE1] => Alun
            [MERGE2] => Llewelyn
            [MERGE3] => Abertawe
        )

)
commented: +1 I was thinking to the same solution but with array_merge() hah +13

Thanks for the replies. I ended up doing something quite simple. Instead of:

$mergeField[] = ['MERGE'.$i.'' => $d];
I did:
$mergeField[$field] = $d;

And that worked nicely. Might be a tad more inefficient that what was suggested here.

Member Avatar for diafol

No need take out email with unset and assign Mergefields = data.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.