dongshai2022 2014-05-27 12:27 采纳率: 100%
浏览 84
已采纳

如何在数组中循环并使用if语句中的每个值

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条回答 默认 最新

  • dpfqy5976 2014-05-27 12:31
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dongwen7187 2014-05-27 12:30
    关注

    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.

    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 arm虚拟机无法和物理机互通
  • ¥15 如何在此代码上增加一个统计学生生源的功能?(语言-c语言)
  • ¥15 Android导航条遮盖异常
  • ¥15 计算机网络技术基础问题
  • ¥15 设置mac系统只能访问指定网站
  • ¥15 西门子博途 s7 1200控制三台步进电机
  • ¥15 基于非参数的方向距离函数求污染物影子价格(有偿)
  • ¥15 vue+element 生成table
  • ¥15 实验 4 FIFO 算法和 LRU 算法-C 程序实现
  • ¥15 有偿拼接大疆精灵4RGB影像