簡體   English   中英

從對象數組的單列創建逗號分隔的字符串

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

我正在使用 foreach 循環從我的數據庫中回顯一些值,如果有意義,我需要從最后一個循環中去除最后一個逗號。

我的循環很簡單,如下

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

哪個回響

result,result,result,result,

我只需要殺死那個討厭的最后一個逗號。

更好:

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

1. 連接到字符串但添加|

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

2.回聲| 僅當不是最后一項

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

3.加載到數組然后內爆

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

4. 連接到字符串然后切到最后| (或rtrim它)

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

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 來修復它,將其初始化為 0,然后讓它在 foreach 循環內遞增。 如果 $i 計數器小於數組/變量的 sizeof() 運算符,則在該循環中放置一個 if、else 和包含逗號的 echo 語句。

我不知道這本身是否會解決您的問題,但它幫助我解決了我的問題。 我意識到這個問題已有多年歷史,但希望這會對其他人有所幫助。 我對 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);

在現代 PHP 中, array_column()允許您隔離對象數組中的一列數據。

代碼:(演示

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

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

輸出:

A,B,C

也就是說,由於您正在迭代一個結果集,那么通過在您的 sql 中調用CONCAT()函數可能會更好地為您服務,以便這些值已經加入到單值結果集中。

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

不那么漂亮,但也有效:

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

另一個聰明的方法是:

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

在這種情況下,在第一循環$passedNULL,不打印。

我知道這是一個舊線程,但是最近出現了這個問題,我想我會使用 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.

在這里玩

我必須這樣做很多,因為我總是試圖將數字輸入到 jplot,我發現將逗號放在循環前面更容易,如下所示:

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

然后使用 substr 切掉第一個字符(逗號),如果您知道字符串的長度會有幫助,我不確定 substr 最大字符的限制是什么。

 echo substr($a,1,10000000);

希望這可以幫助。

$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;
}
?>

這就是我通常所做的,在項目之前而不是之后添加一個逗號,同時忽略第一個循環。

$i = 0;
$string = '';

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

首先使用輸出緩沖獲取所有輸出。 然后,修剪逗號並顯示它。 所以,這樣做:

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

echo rtrim($output, ',');

如果內部循環非常大(並且 OP 在這里發布只是為了簡潔),則輸出緩沖方法會有所幫助,然后在不更改循環內部的情況下使用 OB 會更容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM