[英]Redeclare - repeat function if array has more than one value
function test($str) {
$c = count($str);
if ($c>1) {
foreach ($str as $key => $value) $result .= test($value);
} else {
$result = "<li>$str</li>\n";
}
echo $result ? "<ol>$result</ol>" : null;
}
$ str值可以是這樣的;
$str1 = "apple";
或類似的東西;
$str2 = array("apple","orange","pear");
如果count($ str)大於一個,即$ str是is_array,它將重復$ result。
但這並沒有我想要的。
我收到一個錯誤
理想的輸出為-$ str1;
<ol>
<li>apple</li>
</ol>
理想的輸出將是-$ str2;
<ol>
<li>apple</li>
<li>orange</li>
<li>pear</li>
</ol>
function test($str) {
// Ensure, $str is a good argument of implode()
if ( ! is_array( $str )) {
$str = array( $str );
}
$result = '<li>' . implode( '</li><li>', $str ) . '</li>';
return '<ol>' . $result . '</ol>';
}
備注:您的方法可能返回以下內容:
<ol>
<li>1</li>
<li>
<ol>
<li>1</li>
<li>2</li>
<li>3</li>
</ol>
</li>
<li>3</li>
</ol>
這真的是您想要實現的目標嗎? 是否真的需要創建嵌套的OL
結構?
檢查$str
是否為array ,例如:
function test($str, $first=true) {
if (!is_array($str)) {
$result = "<li>$str</li>\n";
} else {
foreach ($str as $key => $value) $result .= test($value, false);
}
return ($first ? "<ol>$result</ol>" : $result);
}
另請參見此示例 。
===更新===
如果要直接打印,請替換為:
function test($str, $first=true) {
if (!is_array($str)) $result = "<li>$str</li>";
else foreach ($str as $key => $value) $result .= test($value, false);
if ($first) echo "<ol>$result</ol>";
else return $result;
}
另請參見此示例 。
function testInternal($str){
if(is_array($str))
return implode('',array_map('testInternal', $str));
else
return '<li>'.$str.'</li>';
}
function test($str){
echo '<ol>'.testInternal($str).'</ol>';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.