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

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了