I have an array $email like this:
Array
(
[email_id] => [email protected]
)
Array
(
[email_id] => [email protected]
)
Array
(
[email_id] => [email protected]
)
I need this array to be in this format
'[email protected]', '[email protected]', '[email protected]' // RESULT EXPECTED
I am doing this to get my result:
$emails = implode(", " , $email);
But it results in this:
[email protected]@[email protected] // ACTUAL RESULT
What should i do get the result?
5 Answers 5
Try
$email = array(
array('email_id' => '[email protected]'),
array('email_id' => '[email protected]'),
array('email_id' => '[email protected]'),
array('email_id' => '[email protected]'),
);
foreach($email as $id)
{
echo "'".$id['email_id']."',";
}
2 Comments
I'm using Hassaan's technique :
$email = array(
array('email_id' => '[email protected]'),
array('email_id' => '[email protected]'),
array('email_id' => '[email protected]'),
array('email_id' => '[email protected]'),
);
foreach($email as $id){
$emails .= $id['email_id'].",";
}
$emails = substr($emails, 0, strlen($emails) -1 );
echo $emails;
With this technique you will not have the last comma.
Or you can use this technique that I found here
$input = array(
array('email_id' => '[email protected]'),
array('email_id' => '[email protected]'),
array('email_id' => '[email protected]'),
array('email_id' => '[email protected]')
);
echo implode(',', array_map(function ($entry) {
return $entry['email_id'];
}, $input));
Comments
Strange!! It should work.
How you have defined your $email array? Can you provide a code structure?
If you have something like this then it will definitely work.
$email = array('email1','email2');
echo implode(", ",$email);
Comments
You can try php's csv function for it
<?php
$file = fopen("email.csv","w");
foreach ($yourArray as $value)
{
fputcsv($file,explode(',',$value));
}
fclose($file);
?>
Comments
You could also use array_map to reduce the array of arrays into just an array of strings.
$actualEmails = array_map (function ($e) {
return $e ['email_id'];
}, $email);
echo "'" . implode ("','", $actualEmails) . "'";
implodesince all array keys are same.implodewill work if the array is likearray('mail1', 'mail2'). For the time being, use the solution put forward by @Hassan.