2
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) 大于1,即$str is_array,则重复$result。
但它不能按我的意愿工作。
我收到一个错误“无法重新声明 test()(以前在...中声明”)

理想的输出是 - $str1;

<ol>
  <li>apple</li>
</ol>

理想的输出是 - $str2;

<ol>
  <li>apple</li>
  <li>orange</li>
  <li>pear</li>
</ol>
4

3 回答 3

3
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结构吗?

于 2012-07-22T14:09:39.743 回答
1

Check, if $str is an array, e.g.:

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);
}

Also see this example.

=== UPDATE ===

If you want to let it print directly, replace with:

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

Also see this example.

于 2012-07-22T13:30:30.777 回答
1
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>';
}
于 2012-07-22T13:33:55.390 回答