0

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??

Edited by happygeek: removed email address

2
Contributors
3
Replies
31
Views
1 Year
Discussion Span
Last Post by diafol
1
$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
        )

)

Edited by diafol

Votes + Comments
+1 I was thinking to the same solution but with array_merge() hah
0

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.

0

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.