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

前端 未结 14 1324
醉话见心
醉话见心 2020-11-30 07:36

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.

My loop is just simple, as

相关标签:
14条回答
  • 2020-11-30 08:05
    <?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;
    ?>
    
    0 讨论(0)
  • 2020-11-30 08:06

    Not as pretty, but also works:

    $first=true;
    foreach($results as $result){
        if(!$first) { echo ', '; }
        $first=false;
        echo $result->name;
    }
    
    0 讨论(0)
  • 2020-11-30 08:11

    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.

    0 讨论(0)
  • 2020-11-30 08:12
    $result_names = '';
    foreach($results as $result){
        $result_names .= $result->name.',';
    }
    echo rtrim($result_names, ',');
    
    0 讨论(0)
  • 2020-11-30 08:16
    $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;
    
    0 讨论(0)
  • 2020-11-30 08:19

    In modern PHP, array_column() wil allow you to isolate a column of data within an array of objects.

    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.

    0 讨论(0)
提交回复
热议问题