简体   繁体   English

从对象数组的单列创建逗号分隔的字符串

[英]Create a comma-separated string from a single column of an array of objects

I'm using a foreach loop to echo out some values from my database, I need to strip the last comma from the last loop if that makes sense.我正在使用 foreach 循环从我的数据库中回显一些值,如果有意义,我需要从最后一个循环中去除最后一个逗号。

My loop is just simple, as below我的循环很简单,如下

foreach($results as $result){
  echo $result->name.',';
}

Which echos out哪个回响

result,result,result,result,

I just need to kill that pesky last comma.我只需要杀死那个讨厌的最后一个逗号。

Better:更好:

$resultstr = array();
foreach ($results as $result) {
  $resultstr[] = $result->name;
}
echo implode(",",$resultstr);

1. Concat to string but add | 1. 连接到字符串但添加| before

$s = '';
foreach ($results as $result) { 
    if ($s) $s .= '|';
    $s .= $result->name; 
}
echo $s;

2. Echo | 2.回声| only if not last item仅当不是最后一项

$s = '';
$n = count($results);
foreach ($results as $i => $result) { 
    $s .= $result->name;
    if (($i+1) != $n) $s .= '|';
}
echo $s;

3. Load to array and then implode 3.加载到数组然后内爆

$s = array();
foreach ($results as $result) { 
    $s[] = $result->name;
}
echo implode('|', $s);

4. Concat to string then cut last | 4. 连接到字符串然后切到最后| (or rtrim it) (或rtrim它)

$s = '';
foreach ($results as $result) { 
    $s .= $result->name . '|';
}
echo substr($s, 0, -1); # or # echo rtrim($s, '|');

5. Concat string using array_map() 5. 使用array_map()字符串

echo implode('|', array_map(function($result) { return $result->name; }, $results));
$result_names = '';
foreach($results as $result){
    $result_names .= $result->name.',';
}
echo rtrim($result_names, ',');

I've been having the same issue with this similar problem recently.我最近在这个类似的问题上遇到了同样的问题。 I fixed it by using an increment variable $i, initializing it to 0, then having it increment inside the foreach loop.我通过使用增量变量 $i 来修复它,将其初始化为 0,然后让它在 foreach 循环内递增。 Within that loop place an if, else, with the echo statement including a comma if the $i counter is less than the sizeof() operator of your array/variable.如果 $i 计数器小于数组/变量的 sizeof() 运算符,则在该循环中放置一个 if、else 和包含逗号的 echo 语句。

I don't know if this would fix your issue per se, but it helped me with mine.我不知道这本身是否会解决您的问题,但它帮助我解决了我的问题。 I realize this question is years-old, but hopefully this will help someone else.我意识到这个问题已有多年历史,但希望这会对其他人有所帮助。 I'm fairly new to PHP so I didn't quite understand a lot of the Answers that were given before me, though they were quite insightful, particularly the implode one.我对 PHP 还很陌生,所以我不太明白在我之前给出的很多答案,尽管它们很有见地,尤其是内爆的。

$i=0;
foreach ($results as $result) {
    $i++;
    if(sizeof($results) > $i) {
        echo $result . ", ";
    } else {
        echo $result;
    }
}
$string = "";
while ($row = mysql_fetch_array($result)) {
  $string .= $name . ', ';
}
echo substr($string, 0, strlen($string) - 2);

In modern PHP, array_column() wil allow you to isolate a column of data within an array of objects.在现代 PHP 中, array_column()允许您隔离对象数组中的一列数据。

Code: ( Demo )代码:(演示

$results = [
    (object)['name' => 'A'],
    (object)['name' => 'B'],
    (object)['name' => 'C']
];

echo implode(',', array_column($results, 'name'));

Output:输出:

A,B,C

That said, since you are iterating a result set, then you may be better served by calling a CONCAT() function in your sql, so that the values are already joined in the single value result set.也就是说,由于您正在迭代一个结果集,那么通过在您的 sql 中调用CONCAT()函数可能会更好地为您服务,以便这些值已经加入到单值结果集中。

$arraySize = count($results);
for($i=0; $i<$arraySize; $i++)
{
  $comma = ($i<$arraySize) ? ", " : "";
  echo $results[$i]->name.$comma;
}

Not as pretty, but also works:不那么漂亮,但也有效:

$first=true;
foreach($results as $result){
    if(!$first) { echo ', '; }
    $first=false;
    echo $result->name;
}

Another smart way is:另一个聪明的方法是:

foreach($results as $result){
  echo ($passed ? ',' : '') . $result->name;
  $passed = true;
}

In this case at first loop $passed is NULL and , doesn't print.在这种情况下,在第一循环$passedNULL,不打印。

I know this is an old thread, but this came up recently and I thought I'd share my alternate, cleaner way of dealing with it, using next().我知道这是一个旧线程,但是最近出现了这个问题,我想我会使用 next() 来分享我的替代,更清晰的处理方式。

$array = array("A thing", "A whatsit", "eighty flange oscillators");
          
foreach( $array as $value ){
    echo $value;
    $nxt = next($array);
    if($nxt) echo ", "; // commas between each item in the list
    else echo ". And that's it."; // no comma after the last item.
}

// outputs: 
// A thing, A whatsit, eighty flange oscillators. And that's it.

play with it here 在这里玩

I have to do this alot because I'm always trying to feed numbers in to jplot, I find its easier to put the comma in the front of the loop like so:我必须这样做很多,因为我总是试图将数字输入到 jplot,我发现将逗号放在循环前面更容易,如下所示:

foreach($arrayitem as $k){ $string =  $string.",".$k;
 } 

and then chop off the first character (the comma) using substr, it helps if you know a guestimate of long your string will be, I'm not sure what the limit on substr max character is.然后使用 substr 切掉第一个字符(逗号),如果您知道字符串的长度会有帮助,我不确定 substr 最大字符的限制是什么。

 echo substr($a,1,10000000);

hope this helps.希望这可以帮助。

$a[0] = 'John Doe';       
$a[1] = 'Jason statham';       
$a[2] = 'Thomas Anderson';
$size = count($a);
foreach($a as $key=>$name){
    $result .= $name;
    if($size > $key+1) $result .=', ';
}
echo $result;
<?php
$return = array(any array)
$len = count($return);
$str = '';
$i = 1;
foreach($return as $key=>$value)
{
    $str .= '<a href='.$value['cat_url'].'>'.$value['cat_title'].'</a>';
    if($len > $i)
    {
        $str .= ',';
        $i = $i+1;
    }
}
echo $str;
?>
<?php
$i = 1;
$count = count( $results );
foreach( $results as $result ) {
    echo $result->name;
    if ( $i < $count ) echo ", ";                               
    ++$i;
}
?>

This is what I normally do, add a comma before the item rather than after, while ignoring the first loop.这就是我通常所做的,在项目之前而不是之后添加一个逗号,同时忽略第一个循环。

$i = 0;
$string = '';

foreach($array as $item){
    $string .= ($i++ ? ',' : '').$item;
}

First get all the output by using output buffering.首先使用输出缓冲获取所有输出。 Then, trim the comma and display it.然后,修剪逗号并显示它。 So, do it like this:所以,这样做:

ob_start();
foreach($results as $result)
{
   echo $result->name.',';
}
$output = ob_get_clean();

echo rtrim($output, ',');

The output buffering method helps if the inside loop is very big (and OP is posting here just for brevity), then using OB is easier without changing the internals of the loop.如果内部循环非常大(并且 OP 在这里发布只是为了简洁),则输出缓冲方法会有所帮助,然后在不更改循环内部的情况下使用 OB 会更容易。

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

相关问题 将数组列中的唯一值打印为逗号分隔的字符串 - Print unique values from an array column as a comma-separated string 从字符串创建逗号分隔的参数 - create comma-separated arguments from string 逗号分隔的字符串到数组 - comma-separated string to array 从包含相关逗号分隔值的单元素关联数组创建一个新的关联数组 - Create a new associative array from a single-element associative array containing related comma-separated values 如何将多维数组中的列转换为逗号分隔的字符串? - How convert a column from a multi-dimensional array into a comma-separated string? 从逗号分隔的字符串中删除项目 - Remove an item from a comma-separated string 将逗号分隔的单引号字符串字符串转换为 int 数组 - Converting comma-separated string of single-quoted numbers to int array 在单个查询中搜索逗号分隔的MySQL列中的多个值 - Searching multiple values in a Comma-Separated MySQL column in a single query 如何从数组数组(多维数组)加入逗号分隔的字符串? - How to join into a comma-separated string from array of arrays (multidimensional-array)? 从数据库表中提取的逗号分隔值行创建单个值的平面数组 - Create flat array of individual values from rows of comma-separated values fetched from a database table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM