-1

I have a list of skills and industries in a table which is fetched into a multidimensional array like the below. There are over 300 rows in the table:

$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)

...

I'm trying to echo out each industry with the relevant skills in a list to look like the below:

Accountancy, banking and finance
10000083, AAT
10000078, ACCA
10000079, CT600

Business, consulting and management
10000102, WIP

Engineering and manufacturing
10000169, 3D Modelling

Internet and technology
10000095, HTML

At the moment I'm using a foreach so each one is listed one at a time but I really want to group them together. I've looked at array_filter and using a key but just can’t get what I wanted. Is it possible to do this from the array I have?

1 Answers1

1

Sort data by industry then loop (echo title if different from previous one) :

   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"] ;
    }

(You may also add an "order by industry" in your SQL query)

RafH
  • 4,504
  • 2
  • 23
  • 23
  • Thank you, this worked exactly as I wanted :) I changed my select statement to order by industry and then skill then changed your code to this: $lastskill = ''; foreach($skills as $skill) { if ($skill['industry'] !== $lastSkill ) { echo '

    '.$skill['industry'].'

    '; $lastSkill = $skill["industry"]; } echo '
    '.$skill['skill']; }
    – user7269149 Mar 13 '17 at 00:30