dongmeng1868 2014-10-22 03:31
浏览 91
已采纳

尝试循环遍历数组时未定义的偏移量

I need to convert my array:

$tdata = array(11,3,8,12,5,1,9,13,5,7);

Into a string like this:

11-3-8-12-5-1-9-13-5-7

I was able to get it work with:

$i = 0;
$predata = $tdata[0];
foreach ($tdata as $value)
{
    $i++;
    if ($i == 10) {break;}
    $predata.='-'.$tdata[$i];

}

But was wondering if there is an easier way?

I tried something like:

$predata = $tdata[0];

foreach ($tdata as $value)
{
    if($value !== 0) {
        $predata.= '-'.$tdata[$value];
    }
}

but it result in bunch of Undefined Offset errors and incorrect $predata at the end.

So I want to learn once and for all:

  1. How to loop through the entire array starting from index 1 (while excluding index 0)?

  2. Is there a better approach to convert array into string in the fashion described above?

  • 写回答

1条回答 默认 最新

  • douxie4583 2014-10-22 03:32
    关注

    Yes there is a better approach to this task. Use implode():

    $tdata = array(11,3,8,12,5,1,9,13,5,7);
    echo implode('-', $tdata); // this glues all the elements with that particular string.
    

    To answer question #1, You could use a loop and do this:

    $tdata = array(11,3,8,12,5,1,9,13,5,7);
    $out = '';
    foreach ($tdata as $index => $value) { // $value is a copy of each element inside `$tdata`
    // $index is that "key" paired to the value on that element
        if($index != 0) { // if index is zero, skip it
            $out .= $value . '-';
        }
    }
    // This will result into an extra hypen, you could right trim it
    
    echo rtrim($out, '-');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度