duanlanzhi5509 2015-01-20 09:06
浏览 32
已采纳

使用字符在PHP中分组

I have an array like:

    array{
     0 => string 'B.E - ECE',
     1 => string 'B.E - EEE',
     2 => string 'Msc - Maths',
     3 => string 'Msc - Social',
}

So how can I make the array into groups like:

B.E. => ECE, EEE
Msc => Maths,Social

?

I want to do it in PHP. Can anybody help me how to achieve it ?

  • 写回答

2条回答 默认 最新

  • dso0139 2015-01-20 09:18
    关注

    So is your array split by the "-" character?

    so it's Key - Value pairs split by commas?

    Ok -

    (edit: section removed to clarify answer)

    Following conversation and some rearrangement of the question, a second try at a solution, with the above assumptions, try this:

    $array = array {
         0 => string 'B.E - ECE' (length=9)
         1 => string 'B.E - EEE' (length=9)
         2 => string 'Msc - Maths' (length=11)
         3 => string 'Msc - Social' (length=12)
    }
    
    
    foreach ($array as $row){
    $piece = explode("-",$row);
    $key = $piece[0];
    $newArray[$key][] = $piece[1];
    unset($piece);
    }
    unset($row) ///tidy up
    

    This will output two arrays each of two arrays:

    $newArray[Msc] = array("Maths","Social");
    $newArray[B.E] = array("ECE","EEE");
    

    What I did was cause the Foreach loop to automatically add onto the array if the key exists with $newArray[$key][] so that the values are automatically collected by key, and the key is defined as the first half of the original array values.

    Printing:

    To print the result:

    foreach($newArray as $key=>$newRow){
    /// there are two rows in this case, [B.E] and [MSc]
    print $key.":<br>";
    print "<pre>";
    ///<pre> HTML tag makes output use linebreaks and spaces. neater.
    print_r($newRow);
    ///alternatively use var_dump($newRow);
    print "</pre>";
    }
    

    Alternatively if you wish to print a known named variable you can write:

    print_r($newArray['B.E']);
    

    Which will print all the data in that array. print_r is very useful.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程