[英]Separate array of posts by category - PHP
我有一个如下所示的数组,它包含所有帖子,数组中的每个帖子都有一个“类别”。
我想 output 一个类别列表,然后是这些类别中包含的标题(下面是所需 output 的示例)
[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/"
}
}
我想 output 所有类别,然后是其中包含的作业:
例如:
<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>
任何有关实现此结果的最佳方法的帮助或建议将不胜感激!
首先您需要重新排列新数组中的数据,然后使用新数组生成 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>";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.