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
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