1

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!

3
  • 1
    Is this data, by any chance the result of a query, because if it is, odds are you could work on the query, and get what you need that way. It'll probably even be more performant than what you're doing now... Commented Sep 19, 2013 at 13:19
  • Elias won my comment. If this is coming from the database, you're solving this problem at the wrong level. By the way, in your loop the $key=>$item is not necessary for your example. Commented Sep 19, 2013 at 13:20
  • Yes it is coming from the DB the issue is I am dealing with a DB print template ad cant mess with actual db query. That was my first try and I had the query bu the issue is I would end up with my query and the one that is loading by default which I am not supposed to touch. Commented Sep 19, 2013 at 13:23

2 Answers 2

6

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Very nice , but Davids is bit cleaner.
@Benn yes I agree with you also :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.