dongyi4170 2017-02-06 07:42
浏览 76

如何在codeigniter或php上过滤数组

I have an options table

Option_ID | option_Type | Option_Text
----------|-------------|------------
1         | gender      | Male        
2         | gender      | Female      
3         | color       | black
4         | color       | white
5         | color       | red
6         | color       | blue

And I am getting all rows to my controller. But I want to filter array which is loading database rows as option_type

I can read

foreach($optionList as $row){
    if ($row->gender){ echo "<option value='".$row->id."'>".$row->text."</opiton>}
}

But I dont want if statement. Is there any way filter as color without if statement

  • 写回答

1条回答 默认 最新

  • dongse5528 2017-03-13 02:00
    关注

    If I understand you correctly, you don't mind using an if condition in the solution. You just don't want to needlessly iterate while only echoing a few rows in the array.

    I see that you are working with an array of objects, you can cast as array or try to workaround any array functions that choke on objects.

    $options=array(
        array('Option_ID'=>1,'option_Type'=>'gender','Option_Text'=>'Male'),
        array('Option_ID'=>2,'option_Type'=>'gender','Option_Text'=>'Female'),
        array('Option_ID'=>3,'option_Type'=>'color','Option_Text'=>'black'),
        array('Option_ID'=>4,'option_Type'=>'color','Option_Text'=>'white'),
        array('Option_ID'=>5,'option_Type'=>'color','Option_Text'=>'red'),
        array('Option_ID'=>6,'option_Type'=>'color','Option_Text'=>'blue')
    );
    
    // collect all option_Type values, retain unique values, declare filter as $f
    foreach(array_unique(array_column($options,"option_Type")) as $f){
        echo ucfirst($f),": <select name=$f>";
        foreach(array_filter($options,function($a)use($f){if($a["option_Type"]==$f)return $a;}) as $row){
            echo "<option value='",$row["Option_ID"],"'>",$row["Option_Text"],"</option>";
        }
        echo "</select><br><br>";
    }
    

    This will ensure every iteration is useful. Demo


    Non-LINQ Second Attempt (Demo):

    array_filter seems to work for me with my subarrays cast as objects.

    foreach(array_filter($options,function($a){return $a->option_Type=='gender';}) as $o){
        echo "{$o->Option_Text}<br>";
    }
    

    This makes no wasted iterations and displays:

    black
    white
    red
    blue
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题