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

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

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, '-');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?