My array has 12 news items with titles, descriptions and category name
I have only 4 categories ( 3 items each) and need to create categories menu but if I get them from items array I have 12 category names(3x each) as a result. How can I echo category names only once if it was already printed ?
$myarray print:
[0] => Array
(
[title] => Item 1
[desc] => Sed venenatis bibendum nisl, eget iaculi
[cat_title] => Category 1
)
[1] => Array
(
[title] => Item 1
[desc] => Sed venenatis bibendum nisl, eget iaculi
[cat_title] => Category 2
)
[2] => Array
(
[title] => Item 2
[desc] => Sed venenatis bibendum nisl, eget iaculi
[cat_title] => Category 2
)...
loop:
foreach( $myarray as $key=>$item){
echo $item['category_name'];
}
Note: I am not able to know how many categories wil the re be , it can be one or more. Currently there is 4. Any help is appreciated . Thank you!
Map the array categories to a simple array and then remove all duplicate values.
$categories = array_unique(array_map(function($val) {
return $val['cat_title'];
}, $myarray));
foreach($categories as $cat) {
echo $cat;
}
You can create temp array:
$temp = array();
foreach( $myarray as $key=>$item){
if(!in_array($item['category_name'], $temp)){
echo $item['category_name'];
$temp[] = $item['category_name'];
}
}