0

I have the function:

public function onK2AfterDisplayContent(&$item,&$params,$limitstart)
{   
    $cat_id = $this->params['cat_ids'];
    explode(',', $cat_id);

    $view = JRequest::getVar('view');

    if($view === 'item' && $item->catid === $cat_id){
        $db = JFactory::getDbo();
        $query = 'SELECT name FROM #__k2_categories WHERE id='.$item->catid;
        $db->setQuery($query);
        $resultado = $db->loadResult();

        echo '<input class="subscribete" type="button" id="'.$resultado.'-'.$item->id.'" value="Subscribete" data-id="'.$item->id.'"/>';    
    }
}

The variable $cat_id can bring a different amount of values (1 or 1,2,3, nothing, etc..). My if statement should only enter when one of these values exist in $item->catid. How can I accomplish this?

EDIT: $item->catid can only be a single value like "1".

2 Answers 2

3

You can use in_array :

$cat_id = explode(',', $this->params['cat_ids']);
// Don't forget to assign the explode to a value. Otherwise, it won't be usefull...

if (in_array($item->catid, $cat_id)) {
    // Do something
}
Sign up to request clarification or add additional context in comments.

Comments

0

First, you aren't assigning the explode to anything, so nothing changes in that bit of code:

explode(',', $cat_id);

Secondly, if you do assign it, you can then do a simple foreach statement to poke through each bit of data that comes out.

public function onK2AfterDisplayContent(&$item,&$params,$limitstart)
{   
    $cat_id = $this->params['cat_ids'];
    $carArr=explode(',', $cat_id);

    $view = JRequest::getVar('view');

    foreach($catArr as $val)
    {
        if($view == 'item' && $item->catid == $cat_id){
        $db = JFactory::getDbo();
        $query = 'SELECT name FROM #__k2_categories WHERE id='.$item->catid;
        $db->setQuery($query);
        $resultado = $db->loadResult();

        echo '<input class="subscribete" type="button" id="'.$resultado.'-'.$item->id.'" value="Subscribete" data-id="'.$item->id.'"/>';    

    }

    }
}

Edit: After posting, I noticed John's answer about the === operator, which I think might also cause issues - I didn't even notice it first time round, so have changed it to a == instead.

Comments

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.