How do I push individual elements of an array into another array using PHP?

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

$json1 = '{"found":1,"email":"email1@domain.com","error":"","rd":"email2@domain.com"}';
$json2 = '{"found":1,"email":"email1@domain.com,email2@domain.com","error":"","rd":"email3@domain.com,email4@domain.com"}';

In the first case, the parameters emailand rdhave only one email address. In the second case, the same two parameters have several recipients.

I need to receive emails from each parameter and add it to an existing array:

$recipients = array('support@domain.com');

I can make it work with a variable $json1using the following code:

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

The second JSON option is placed less often, but I still need the same code to work in both instances. And currently, if I use the above code with second JSON data, it returns this:

Array
(
    [0] => support@sculpturehospitality.com
    [1] => email3@domain.com,email4@domain.com
    [2] => email1@domain.com,email2@domain.com
)

. - , ?

:

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

+4
2

explode() ,

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

, array_merge() array_push(), , :

array_push():

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

array_push($array, $singleValue);

:

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

array_push($array, $secondArray);

:

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);

:

: array_merge(): # 2

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

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

:

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

PHP explode().

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

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

$emailPieces , , rd.

+1

Source: https://habr.com/ru/post/1620414/


All Articles