我需要转换我的数组:
$tdata = array(11,3,8,12,5,1,9,13,5,7);
Run Code Online (Sandbox Code Playgroud)
进入这样的字符串:
11-3-8-12-5-1-9-13-5-7
Run Code Online (Sandbox Code Playgroud)
我能够使用它:
$i = 0;
$predata = $tdata[0];
foreach ($tdata as $value)
{
$i++;
if ($i == 10) {break;}
$predata.='-'.$tdata[$i];
}
Run Code Online (Sandbox Code Playgroud)
但是想知道是否有更简单的方法?
我尝试过类似的东西:
$predata = $tdata[0];
foreach ($tdata as $value)
{
if($value !== 0) {
$predata.= '-'.$tdata[$value];
}
}
Run Code Online (Sandbox Code Playgroud)
但它最终导致一堆Undefined Offset错误和错误$predata.
所以我想一劳永逸地学习:
如何从索引1开始循环遍历整个数组(同时排除索引0)?
有没有更好的方法将数组转换为上述方式的字符串?
是的,有更好的方法来完成这项任务.用途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.
Run Code Online (Sandbox Code Playgroud)
要回答问题#1,您可以使用循环并执行以下操作:
$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, '-');
Run Code Online (Sandbox Code Playgroud)