phpwordpresskeycategoriesarray-intersect

How to compare an array of list of keys with an array of "cat_name" of wordpress post with array_intersect


i have created this code :

 <?php 
             $lisections = array('anglais','boxe-thai','Cyclotourisme','Danse-modernjazz–grs–classique','danse-sportive','dessin-peinture','escrime','Espagnol','gym-tonic','gymnastique-de-detente','gymnastique-enfantine-et-sportive','Gymnastique-senior','handball','hatha-yoga','histoire-de-lart','judo - ju jitsu','Karate','kendo-iaido','natation','ninjutsu','petanque','photo-club','randonnees-pedestres','refection-fauteuils','Sportives','subaquatique','tennis-de-table','tennis-de-table–senior','Tir','gym-dentretient-top-gym','sections-arts-martiaux','sections-langues','sections-gymnastique', 'section-aquatique','section-tennisdetable' );
            foreach((get_the_category()) as $cat) { 
                                $displaycat[] = $cat->cat_name . ' '; 
             }
              //print_r($displaycat);
            $onesection=array_intersect($lisections,$displaycat);
            print_r($onesection);?>

but it doesn't work.

$displaycat display that : Array ( [0] => Accueil [1] => Evénements [2] => hatha-yoga [3] => Sections ).

The result of print_r($onesection); is an empty array instead of Array([0] => hatha-yoga.

My target is to get one of categories name "hatha-yoga" of one post to generate a link to return to the main page of this section "hatha-yoga".


Solution

  • Your $displaycat entries have a trailing space ($displaycat[] = $cat->cat_name . ' ';). Your $lisections don't.

    Try $displaycat[] = $cat->cat_name; (without the concatenation).