繁体   English   中英

重新声明-如果数组具有多个值,则重复函数

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM