简体   繁体   中英

Store Associative Array values into comma-separated string

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

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

use join() or impode() is alias

like

$selected_sizes_comma_seprated = join(',', $selected_sizes);

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

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