简体   繁体   English

在PHP中将多维数组放大为单个逗号分隔的列表

[英]Implode Multi Dimensional Array to a single comma separated list in PHP

If I have an array like: 如果我有一个像这样的数组:

Array ( [0] => abcdef )
Array ( [0] => abcdef [1] => abcdef )
Array ( [0] => abcdef [1] => abcdef [2] => abcdef )
Array ( [0] => abcdef [1] => qwerty ) 

And want to create a comma separated list like: 并想要创建一个逗号分隔的列表,例如:

abcdef, abcdef, abcdef, abcdef, abcdef, abcdef, abcdef, qwerty

How would I do this? 我该怎么做?

When I try and implode the array like this: 当我尝试像这样分解数组时:

while($row = mysql_fetch_array($search)){ 
    $row2 = $row['scholarshipid']; 
    $newarray = unserialize($row2);
    $unique_array = array_unique($newarray, SORT_REGULAR);
    $commaList = implode(', ', $unique_array);
    echo "$commaList";
    //print_r($newarray); 
} 

$commaList = implode(', ', $unique_array);

I get: 我得到:

abcdefabcdefabcdefabcdef, qwerty

As from the comments it turns out that the output which you show us comes from a loop. 评论中可以看出,您显示给我们的输出来自循环。 So you first have to collect all arrays in each iteration into 1 variable, which you then can implode, eg 因此,您首先必须将每次迭代中的所有数组收集到1个变量中,然后可以将其内爆,例如

$result = [];

while($row = mysql_fetch_array($search)){
    $row2 = $row['scholarshipid'];
    $newarray = unserialize($row2);
    $unique_array = array_unique($newarray, SORT_REGULAR);
    $result = array_merge($result, $unique_array);
}

echo implode(",", $result);

you can do it like this UPDATE 你可以像这样更新

$temp = array();
while($row = mysql_fetch_array($search)){ 
    $row2 = $row['scholarshipid']; 
    $newarray = unserialize($row2);
    $temp = array_merge($temp, $newarray);

}
$commaList = implode(', ', $temp);
print_r($commaList);

and it's all done :P 一切都完成了:P

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

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