dongshou7903
2014-05-29 06:58
浏览 40
已采纳

将关联数组值存储为逗号分隔的字符串

I have an associative array and I can store its values comma-separated, in a string.

Associative Array has keys/values

0 => 1
1 => 3

I have tried this

$selected_sizes_comma_seprated = "";
foreach ($selected_sizes as $size) {
    $selected_sizes_comma_seprated .= $size.',';
}
// Remove last comma in string
$selected_sizes_comma_seprated = substr($selected_sizes_comma_seprated, 0,-1);

This works fine as I want.

My question is that is there any other better solution to achieve this

图片转代码服务由CSDN问答提供 功能建议

我有一个关联数组,我可以用字符串逗号分隔它的值。 \ n

关联数组具有 / values

  0 =>  1 
1 =>  3 
   
 
 

我试过这个

  $ selected_sizes_comma_seprated =“”; 
foreach($ selected_sizes为$ size)  ){
 $ selected_sizes_comma_seprated。= $ size。','; 
} 
 //删除字符串中的最后一个逗号
 $ selected_sizes_comma_seprated = substr($ selected_sizes_comma_seprated,0,-1); 
  <  / pre> 
 
 

这样可以正常使用。

我的问题是,还有其他更好的解决方案来实现这个目标

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongmuyuan3046 2014-05-29 07:00
    已采纳

    implode() does just that:

    $selected_sizes = array(0 => 1, 1 => 3);
    
    $selected_sizes_comma_seprated = implode(',', $selected_sizes);
    
    echo $selected_sizes_comma_seprated; // 1,3
    

    See demo

    已采纳该答案
    打赏 评论
  • doudouba4520 2014-05-29 07:00

    use join() or impode() is alias

    like

    $selected_sizes_comma_seprated = join(',', $selected_sizes);
    
    打赏 评论
  • doubaoxue5788 2014-05-29 07:03

    PHP has it own function to generate CSV file fputcsv()

    <?php
    
    $list = array (
        array('aaa', 'bbb', 'ccc', 'dddd'),
        array('123', '456', '789'),
        array('"aaa"', '"bbb"')
    );
    
    $fp = fopen('file.csv', 'w');
    
    foreach ($list as $fields) {
        fputcsv($fp, $fields);
    }
    
    fclose($fp);
    ?>
    

    For more reference http://www.php.net/manual/en/function.fputcsv.php

    打赏 评论

相关推荐 更多相似问题