Tom Nolan
Tom Nolan

Reputation: 1957

How do I push individual array items into another array with PHP?

I have a post call that returns JSON in one of two ways:

$json1 = '{"found":1,"email":"[email protected]","error":"","rd":"[email protected]"}';
$json2 = '{"found":1,"email":"[email protected],[email protected]","error":"","rd":"[email protected],[email protected]"}';

In the first, the email and rd parameters each only have one email address. In the second, those same two parameters have multiple recipients each.

I need to take the emails from each parameter and add it to an array that already exists:

$recipients = array('[email protected]');

I can get it to work with the $json1 variable using the following code:

array_push($recipients, $obj->{'rd'}, $obj->{'email'});

The second JSON option is posted more rarely, but I still need the same code to work for both instances. And currently, if I use the above code with the second JSON data it returns this:

Array
(
    [0] => [email protected]
    [1] => [email protected],[email protected]
    [2] => [email protected],[email protected]
)

Which has multiple emails in the same parameter. Does anyone have any insight on how I can separate the emails within each array item?

A working example:

http://sandbox.onlinephpfunctions.com/code/24c4a1eaea98566b65cd36e221dd1f185e820ea6

Upvotes: 4

Views: 131

Answers (2)

Rizier123
Rizier123

Reputation: 59701

Just explode() your property by a comma and add them to the array, e.g.

$recipients = array_merge($recipients, explode(",", $obj->rd)
                                     , explode(",", $obj->email) /*,  ... */);

Also note, that I now use array_merge() instead of array_push(), since you don't have a single value anymore, but an array with the new elements:

array_push():

//Single value
$array = ["First element"];
$singleValue = "Second element";

array_push($array, $singleValue);

output:

Array( [0] => First element [1] => Second element)
//Array
$array = ["First element"];
$secondArray= ["Second element", "And third element"];

array_push($array, $secondArray);

output:

Array( [0] => First element [1] => Array( [0] => Second element [1] => And third element))

array_merge():

//Single value
$array = ["First element"];
$singleValue = "Second element";

$array = array_merge($array, $singleValue);

output:

Warning: array_merge(): Argument #2 is not an array

//Array
$array = ["First element"];
$secondArray= ["Second element", "And third element"];

$array = array_merge($array, $secondArray);

output:

Array( [0] => First element [1] => Second element [2] => And third element)

Upvotes: 5

dchayka
dchayka

Reputation: 1302

Use PHP's function explode().

http://php.net/manual/en/function.explode.php

$emailPieces = explode(",", [string_with_multiple_emails]);

$emailPieces will contains an array consisting of each email address provided in rd string.

Upvotes: 1

Related Questions