gpt4 book ai didi

php - 尝试遍历数组时 undefined offset

转载 作者:行者123 更新时间:2023-12-03 23:06:57 26 4
gpt4 key购买 nike

我需要转换我的数组:

$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];
}
}

但它会导致一堆 Undefined Offset 错误和最后不正确的 $predata

所以我想一劳永逸地学习:

  1. 如何从索引 1 开始遍历整个数组(不包括索引 0)?

  2. 是否有更好的方法以上述方式将数组转换为字符串?

最佳答案

是的,有更好的方法来完成这项任务。使用 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.

要回答问题 #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, '-');

关于php - 尝试遍历数组时 undefined offset ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26499899/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com