简体   繁体   English

将数组拆分为逗号分隔的值

[英]split array into comma separated values

I have an array $email like this: 我有一个像这样的数组$email

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 : 我正在使用Hassaan的技术:

$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? 您如何定义$email数组? 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的csv函数

<?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. 您也可以使用array_map将数组的数组简化为字符串数组。

$actualEmails = array_map (function ($e) {
    return $e ['email_id'];
}, $email);
echo "'" . implode ("','", $actualEmails) . "'";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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