PHP在循环或foreach中按值回显数组

时间:2017-03-13 00:01:00

标签: php arrays foreach

我有一个表中的技能和行业列表,它被提取到如下所示的多维数组中。表中有超过300行:

$skills = 
    [0] => Array ([rowID] => 10000169 [industry] => Engineering and manufacturing [skill] => 3D Modelling)
    [1] => Array ([rowID] => 10000083 [industry] => Accountancy, banking and finance [skill] => AAT)
    [2] => Array ([rowID] => 10000079 [industry] => Accountancy, banking and finance [skill] => CT600)
    [3] => Array ([rowID] => 10000102 [industry] => Business, consulting and management [skill] => WIP)
    [4] => Array ([rowID] => 10000078 [industry] => Accountancy, banking and finance [skill] => ACCA)
    [5] => Array ([rowID] => 10000095 [industry] => Internet and technology [skill] => HTML)

...

我试图用列表中的相关技能回应每个行业,如下所示:

会计,银行和金融
10000083,AAT
10000078,ACCA
10000079,CT600

商业,咨询和管理
10000102,WIP

工程与制造
10000169,3D建模

互联网和技术
10000095,HTML

目前我正在使用foreach,所以每次都列出一个,但我真的想将它们组合在一起。我看过array_filter并使用了一个键,但却无法得到我想要的东西。是否可以从我拥有的数组中做到这一点?

1 个答案:

答案 0 :(得分:1)

按行业排序数据然后循环(如果与前一个不同,则回显标题):

   function cmp($a, $b)
    {
        return strcmp($a["industry"], $b["industry"]);
    }

    usort($skills, "cmp");
    $lastSkill = "";
    foreach($skills as $skill) {
     if ($skill["industry"] !== $lastSkill ) {
      echo "<h1>" . $skill["industry"] . "</h1>";
      $lastSkill = $skill["industry"];
     }
     echo "<br> - " . $skill["skill"] ;
    }

(您也可以在SQL查询中添加&#34; order by industry&#34;)