我正在编写一个PHP函数,它将采用以下格式的数组:
array(
'one',
'two',
'three'
)
并回显以下字符串:
one
one-two
one-two-three
我无法弄清楚如何做到这一点。我尝试使用变量存储前一个变量然后使用它,但它只适用于一个:
$previous = null;
for($i = 0; $i < count($list); $i++) {
echo ($previous != null ? $route[$previous] . "-" : '') . $route[$i];
$previous = $i;
}
对外输出:
one
two
two-three
无论如何,这种方法可能效率低下,因为这个脚本在技术上应该能够处理任何长度的数组。
有人可以帮忙吗?
答案 0 :(得分:6)
for ($i = 1, $length = count($array); $i <= $length; $i++) {
echo join('-', array_slice($array, 0, $i)), PHP_EOL;
}
答案 1 :(得分:3)
$arr = array('one', 'two', 'three');
foreach (array_keys($arr) as $index) {
$result = array();
foreach ($arr as $key => $val) {
if ($key <= $index) {
$result[] = $val;
}
}
echo implode('-', $result) . '<br />';
}
答案 2 :(得分:3)
你正在比较0!= null,问题来自与只有一个=的比较,试试!==,它应该有效。
答案 3 :(得分:2)
另一个:
$data = array('one','two','three');
$str = '';
$len = count($data);
for ($i=0; $i<$len;$i++){
$delim = ($i > 0) ? '-' : '';
$str .= $delim . $data[$i];
echo $str .'<br>';
}
答案 4 :(得分:2)
我们可以使用array_shift()
来从数组中提取第一个元素。然后我们可以迭代这些值并将它们附加到一个字符串:
<?php
$array = array(
'one',
'two',
'three'
);
// Get the first element from the array (it will be removed from the array)
$string = array_shift($array);
echo $string."\n";
foreach ($array as $word) {
$string = implode('-', array($string, $word));
echo $string."\n";
}
输出:
one
one-two
one-two-three
答案 5 :(得分:2)
$arr = ['one','two','three'];
doSomething($arr);
function doSomething($arr) {
foreach($arr as $key=>$val) {
$s = array_slice($arr,0,($key+1));
echo implode('-',$s) . "<br>";
}
}
答案 6 :(得分:1)
使用array_slice
和implode
函数
foreach($arr as $key => $value){
echo implode("-",array_slice($arr, 0, $key+1))."<br/>";
}
O / P
one
one-two
one-two-three