dongqu4443
dongqu4443
2014-11-05 00:58

如何在PHP中将多个数字连接在一起作为字符串?

已采纳

I need to create a comma separated string of numbers.

The issue I'm running into is that, in the end, I'm getting a total of all the numbers when it should be like:

2, 10, 35, 56, 67', etc.

Here's what I'm doing:

$field_ids = '';

// begin while loop
<?php $field_ids = bp_get_the_profile_field_ids(); ?>
// end while loop

// begin while loop
<?php $field_ids += bp_get_the_profile_field_ids(); ?>
// end while loop

<input type="hidden" name="field_ids" id="field_ids" value="<?php echo $field_ids; ?>">

How can I get this:

<input type="hidden" name="field_ids" id="field_ids" value="2, 10, 35, 56, 67">

instead of this:

<input type="hidden" name="field_ids" id="field_ids" value="170">
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dpc57092 dpc57092 7年前

    Yes you could gather them as an array, then use implode() to do this:

    $field_ids = array(); // initialize as array
    
    while(...) { // begin while loop block
        $field_ids[] = bp_get_the_profile_field_ids(); // push it inside
    } // end while loop block
    
    $field_ids = implode(', ', $field_ids); // implode/glue those ids by comma
    
    <input type="hidden" name="field_ids" id="field_ids" value="<?php echo $field_ids; ?>">
    

    By using += you're continually adding them up until the end of the loop resulting to its summation.

    点赞 评论 复制链接分享
  • doumeng3080 doumeng3080 7年前

    Don't use this operator += use this: .=

    So instead of this:

    <?php $field_ids += bp_get_the_profile_field_ids(); ?>
    

    write this:

    <?php $field_ids .= bp_get_the_profile_field_ids(); . ", " ?>
    
    点赞 评论 复制链接分享

相关推荐