简体   繁体   English

防止在打印值时打印关键索引-PHP

[英]Prevent printing key indexes while printing the value - PHP

Hi I have an array like this: 嗨,我有一个像这样的数组:

array(
  'Home' => array(
    'About',
    'Contact'
  ),
  'News'
);

I wrote this to printing them: 我写这是为了打印它们:

function show($arr){
    foreach($arr as $key => $value){
      echo "\n<ul>\n<li>\n" . $key;
      if( ! empty($value)){
        if(is_array($value)){
          show($value);
        }else{
          echo $value;
        }
      }
      echo "\n</li>\n</ul>\n";
    }
}

My problem is when I try to echo $value It'll print something like this: 我的问题是当我尝试echo $value它将打印如下内容:

Home
  0About
  1Contact
0News

I tried to echo $key where the echo $value is here now and I understood it's the key index which is gonna write before the News field or any field that is not an array. 我试图在这里显示echo $value地方echo $key ,我知道它是要在News字段或任何非数组字段之前写入的键索引。 I fixed it with turning the single fields to this: 我通过将单个字段更改为此来解决它:

array(
  'Home' => array(
    'About' => **array()**,
    'Contact' => **array()**
  ),
  'News' => **array()**
);

But I don't want to define additional empty arrays! 但我不想定义其他空数组!

Peace Out! 和平了!

 function show($arr){
     foreach($arr as $key => $value){
       echo "\n<ul>\n<li>"; 
       if( ! empty($value)){
         if(is_array($value)){
          echo '\n'.$key;
           show($value);
         }else{
           echo $value;
         }
       }
       echo "\n</li>\n</ul>\n";
     } }

I would say you have to change the place of you echo (of the $key). 我要说的是,您必须更改($ key)回显的位置。 If it's not an array, you don't care about the key, right ? 如果它不是数组,那么您就不必关心键,对吗?

function show($arr){
foreach($arr as $key => $value){
  if (is_numeric($key))
  echo "\n<ul>\n<li>\n";
  else
  echo "\n<ul>\n<li>\n" . $key;
  if( ! empty($value)){
    if(is_array($value)){
      show($value);
    }else{
      echo $value;
    }
  }
  echo "\n</li>\n</ul>\n";
}
}

I guess is_numeric should solve your problem. 我猜is_numeric应该可以解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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