drmy1050 2014-11-22 12:27
浏览 6
已采纳

foreach循环中的Foreach循环?

I have a list of names and each name consist of 2-4 words: name, (if exist) middle name(s), surname.

These are the names:

  • Ali Yilmaz
  • Taha Ugur Unal
  • Omer Ibrahim Tahsin Son
  • Recai Sahin

etc.

I want to print this names as this: Surname, name middle name(s) (if exist)

The names above will be:

  • Ali Yilmaz -> Yilmaz, Ali
  • Taha Ugur Unal -> Unal, Taha Ugur
  • Omer Ibrahim Tahsin Son -> Son, Omer Ibrahim Tahsin
  • Recai Sahin -> Sahin, Recai

etc.

If I had only one name I can use that code:

    <?php $exp1 = explode(" ", $author1); ?>        
    <?php if (count($exp1) == 2) {?>
    <?php print ($exp1[1] .', ' .$exp1[0]); ?>

    <?php } elseif (count($exp1) == 3) {?>
    <?php print ($exp1[2] .', ' .$exp1[0] .' ' .$exp1[1]); ?>

    <?php } elseif (count($exp1) == 4) {?>
    <?php print ($exp1[3] .', ' .$exp1[0] .' ' .$exp1[1] .' ' .$exp1[2]); ?>        

    <?php }?>


Each page can have different numbers of author and I thought I could use foreach to apply the above code for each author name but I couldn't do this.

I tried a piece of code such that:

        <?php foreach $author as $obj): ?>
            <?php $a = explode (" ", $obj) ?> 
        <?php endforeach ?>
        ...


But it gives error:

explode() expects parameter 2 to be string, array given.

How can I do this?

  • 写回答

4条回答 默认 最新

  • dongliqian6245 2014-11-22 12:34
    关注
    <?php
    $names = array(
      'Ali Yilmaz',
      'Taha Ugur Unal',
      'Omer Ibrahim Tahsin Son',
      'Recai Sahin'
    
    );
    
    // First you should iterate through:
    foreach ($names as $name) {
      // and now, let make the job
      // split by words
      $parts = explode(' ', $name);
      if (count($parts) == 1) {
        echo "{$name}<br/>";
        continue;
      }
      // get last word
      $last = array_pop($parts);
      // Print last one, comma, and rest of name
      echo "{$last}, " . implode(' ', $parts) . "<br/>";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译