Php 尝试循环数组时未定义的偏移量
我需要转换我的阵列:Php 尝试循环数组时未定义的偏移量,php,arrays,Php,Arrays,我需要转换我的阵列: $tdata = array(11,3,8,12,5,1,9,13,5,7); 变成这样的字符串: 11-3-8-12-5-1-9-13-5-7 我能够通过以下方式使其工作: $i = 0; $predata = $tdata[0]; foreach ($tdata as $value) { $i++; if ($i == 10) {break;} $predata.='-'.$tdata[$i]; } 但我想知道是否有更简单的方法 我试过这
$tdata = array(11,3,8,12,5,1,9,13,5,7);
变成这样的字符串:
11-3-8-12-5-1-9-13-5-7
我能够通过以下方式使其工作:
$i = 0;
$predata = $tdata[0];
foreach ($tdata as $value)
{
$i++;
if ($i == 10) {break;}
$predata.='-'.$tdata[$i];
}
但我想知道是否有更简单的方法
我试过这样的方法:
$predata = $tdata[0];
foreach ($tdata as $value)
{
if($value !== 0) {
$predata.= '-'.$tdata[$value];
}
}
但是,它会导致大量未定义的偏移量错误,并在最后导致不正确的$predata
所以我想一劳永逸地学习:
是的,有更好的方法来完成这项任务。使用: 要回答问题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, '-');
什么????这么简单????当一直有一个字符串解决方案时,我对这些循环非常着迷。。。谢谢大家!@Acidon是的,PHP中有一个内置函数已经完成了这项工作:)。很高兴我能帮忙啊,也谢谢你回答第一个问题,你就是那个人!使用
trim
非常棒,也适用于我的情况:)上帝,我爱PHP!
$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, '-');