dp19001 2012-11-14 18:20
浏览 167
已采纳

foreach中的爆炸变量,但在第一个数组之后,数组从1开始而不是0

I am taking a list of names and putting the last name first. When I use explode to create the $name array, the first name has the first name in array position 0 and the last name at position 1, but the other names all start with first name at position 1 and last name at position 2.

I copied this code from another script that does similar things, but in that code all of the first names, including the first instance, start at number 1 (at least its consistent).

I'm guessing I'm missing something fundamental. I appreciate your assistance.

The code follows.

$_511a = 'Maria Smith, Lance Farquardt, Daniel Berquist, John Barton, Milo Silver';
echo '511a: ' . $_511a . '<br />';
$castsplit = explode(',' , $_511a);
foreach($castsplit as $cast) {
    $name = explode(' ',$cast);
    $lastname = end($name);
    if(count($name) >= 4){
        $middlename = $name[2];
    } else {
        $middlename = null;   
    }
    $firstname = $name[1];
    if($middlename){
        $castmembers[] = $lastname . ', ' . $firstname .  ' ' . $middlename;
    } else {
        $castmembers[] = $lastname . ', ' . $firstname;
    }
}
echo "Corrected names: <br />";
foreach($castmembers as $castmember) {
    echo $castmember . '<br />';
}
  • 写回答

4条回答 默认 最新

  • doutou7549 2012-11-14 18:39
    关注

    You have spaces in between the string '$_511a' so explode function must have a space also. so the index of $name will also be changed because now we have the first element on 0 index.

    change code

    $castsplit = explode(',' , $_511a);
    

    to

    $castsplit = explode(', ' , $_511a);
    

    and

    $firstname = $name[1];
    

    to

    $firstname = $name[0];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Llama如何调用shell或者Python
  • ¥20 eclipse连接sap后代码跑出来空白
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案