简体   繁体   中英

split array into comma separated values

I have an array $email like this:

Array
(
    [email_id] => bob2@example.com
)
Array
(
    [email_id] => bob3@example.com
)
Array
(
    [email_id] => bob4@example.com
)

I need this array to be in this format

'bob2@example.com', 'bob3@example.com', 'bob4@example.com' // RESULT EXPECTED

I am doing this to get my result:

$emails = implode(", " , $email);

But it results in this:

bob2@example.combob3@example.combob4@example.com // ACTUAL RESULT

What should i do get the result?

Try

$email = array(
    array('email_id' => 'bob2@gmail.com'),
    array('email_id' => 'bob3@gmail.com'),
    array('email_id' => 'bob4@gmail.com'),
    array('email_id' => 'bob5@gmail.com'),
    );

foreach($email as $id)
{
    echo "'".$id['email_id']."',";
}

I'm using Hassaan's technique :

$email = array(
    array('email_id' => 'bob2@gmail.com'),
    array('email_id' => 'bob3@gmail.com'),
    array('email_id' => 'bob4@gmail.com'),
    array('email_id' => 'bob5@gmail.com'),
);

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' => 'bob2@gmail.com'),
    array('email_id' => 'bob3@gmail.com'),
    array('email_id' => 'bob4@gmail.com'),
    array('email_id' => 'bob5@gmail.com')
);

echo implode(',', array_map(function ($entry) {
  return $entry['email_id'];
}, $input));

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

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

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) . "'";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM