-1

I have an array that looks like the following, it contains all posts, each post in the array has a 'category'.

I'd like to output a list of categories, and then the titles that are contained within those categories (Example of desired output below)

  [0]=>
  array(3) {
    ["title"]=>
    string(10) "Test Job 8"
    ["category"]=>
    string(5) "Cat 3"
    ["link"]=>
    string(46) "https://example.com/vacancies/test-job-8/"
  }
  [1]=>
  array(3) {
    ["title"]=>
    string(10) "Test Job 7"
    ["category"]=>
    string(5) "Cat 3"
    ["link"]=>
    string(46) "https://example.com/vacancies/test-job-7/"
  }
  [2]=>
  array(3) {
    ["title"]=>
    string(10) "Test Job 6"
    ["category"]=>
    string(5) "Cat 3"
    ["link"]=>
    string(46) "https://example.com/vacancies/test-job-6/"
  }
  [3]=>
  array(3) {
    ["title"]=>
    string(10) "Test Job 5"
    ["category"]=>
    string(5) "Cat 2"
    ["link"]=>
    string(46) "https://example.com/vacancies/test-job-5/"
  }
  [4]=>
  array(3) {
    ["title"]=>
    string(10) "Test Job 4"
    ["category"]=>
    string(5) "Cat 2"
    ["link"]=>
    string(46) "https://example.com/vacancies/test-job-4/"
  }
  [5]=>
  array(3) {
    ["title"]=>
    string(10) "Test Job 3"
    ["category"]=>
    string(5) "Cat 2"
    ["link"]=>
    string(46) "https://example.com/vacancies/test-job-3/"
  }
  [6]=>
  array(3) {
    ["title"]=>
    string(10) "Test Job 2"
    ["category"]=>
    string(5) "Cat 1"
    ["link"]=>
    string(46) "https://example.com/vacancies/test-job-2/"
  }
  [7]=>
  array(3) {
    ["title"]=>
    string(10) "Test Job 1"
    ["category"]=>
    string(5) "Cat 1"
    ["link"]=>
    string(46) "https://example.com/vacancies/test-job-1/"
  }
}

I'd like to output all the categories, followed by the jobs contained within them:

For example:

<h2>Cat 1:</h2>
<p>Test Job 1</p>
<p>Test Job 2</p>

<h2>Cat 2:</h2>
<p>Test Job 3</p>
<p>Test Job 4</p>
<p>Test Job 5</p>


<h2>Cat 3:</h2>
<p>Test Job 6</p>
<p>Test Job 7</p>
<p>Test Job 8</p>

Any help or advice on the best way to achieve this result would be hugely appreciated!

fish_r
  • 667
  • 1
  • 6
  • 23

1 Answers1

0

At first you need to rearrange the data in a new array and then use the new array to generate the output

foreach ($data as $job) {
    $output[$job['category']] = $job['title'];
}

$prev_category = null;
$output = [];
foreach ($output as $category=>$job) {
    if($prev_category!==$category){
        echo "<h2>$category</h2>>";
        $prev_category=$category;
    }
    echo "<p>$job</p>";
}
Roberto Braga
  • 569
  • 3
  • 8