ratscoder
ratscoder

Reputation: 13

How to get id in array with search?

We have lists of categories (ID and Category Name) in variable $categories. However, since the category names are often ambiguous, we have another variables mapping variations of the category name to its original category name in $mapped_categories. For example, category name “Pancakes” mapped to original category name “Pancakes / Waffles / Crepes”, therefore have category ID of 133.

Source http://pastebin.com/yWPh4LkW

Example :
foreach($input_categories as $input_category)
{
   if(in_array($input_category, $categories))
            echo array_search($input_category, $categories).'<br/>';
}

$mapped_categories can not be read, Help me to get it.

Upvotes: 1

Views: 53

Answers (2)

Robert
Robert

Reputation: 20286

I think you need intersection

var_dump(array_intersect($input_categories, $categories));

However, I don't know what $mapped_categories are because it is not clear from your question.

Other possible solution what you may look for is:

$intersected = array_intersect($input_categories, array_keys($mapped_categories));
$found = [];
foreach ($intersected as $el) {
   $found[] = array_search($mapped_categories[$el], $categories);
}

It will return keys of found categories based on mapping.

Upvotes: 2

codisfy
codisfy

Reputation: 2183

You problem statement is not clear but I am taking a guess.

If an element from your input_categories, matches one of the categories then you return its index, otherwise you check the $mapped_categories for its mappedCatgory and then search the $input_categories and return the index(id)

So your code should be something like :

foreach($input_categories as $input_category) {
    if(in_array($input_category, $categories)) {
                echo array_search($input_category, $categories).'<br/>';
    } else if (!empty($mapped_categories[$input_category])) {
         $mappedCategory = $mapped_categories[$input_category];
         if(in_array($mappedCategory, $categories)) {
                echo array_search($mappedCategory, $categories).'<br/>';
         }
    } else {
       echo 'Not Found';
    }
}

Upvotes: 0

Related Questions