dongqu4443 2014-11-05 00:58
浏览 438
已采纳

如何在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 2014-11-05 01:00
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 simulink中怎么使用solve函数?
  • ¥30 dspbuilder中使用signalcompiler时报错Error during compilation: Fitter failed,求解决办法
  • ¥15 gwas 分析-数据质控之过滤稀有突变中出现的问题
  • ¥15 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题