multiple select in 2 dimensional array in php - php

In PHP, I am having 2 array
$ex1 = array(a,b,c,d,e,f,g,h);
$ex2 = array(c,e,f);
Here how can I integrate this with multiple select option in PHP page
Here ex1 is the multiple select array like
<select multiple name=slt[]>
</select>
And ex2 values are the chosen listing options

Something like:
<?php
$ex1 = array('a','b','c','d','e','f','g','h');
$ex2 = array('c','e','f');
echo "<select multiple name=slt[]>";
foreach($ex1 as $val){
//in_array() checks if value from 1st array ($val) is present
//anywhere in the second array ($ex2)
//if yes, that option will be selected. I'm using ternary operator
//here instead of if statement
$selected = (in_array($val,$ex2))?' selected':'';
echo "<option value='".$val."'$selected>".$val."</option>";
}
echo "</select>";
?>
PHP Demo
Output Fiddle

I'm not sure about what you want to do, but here's an idea :
$ex1 = array("a","b","c","d","e","f","g","h");
echo "<select multiple>";
foreach( $ex1 as $value ){
echo "<option value='$value'>$value</option>";
}
echo "</select>";

Try running it:
<?php
$ex1 = array('a','b','c','d','e','f','g','h');
$ex2 = array('c','e','f');
?>
<select multiple name=slt[]>
<?php
foreach ($ex1 as $option) {
$active = false;
foreach($ex2 as $selected){
if($option == $selected){
$active = true;
}
}
?>
<option value="<?php echo $option; ?>" <?php if($active===true) echo "selected"; ?>><?php echo $option; ?></option>
<?php
}
?>
</select>

Related

Looping the array in select

I have this kind of array shown in Picture. How can i insert the values in the select option as
<option value="7">7</option>
<option value="13000">13000</option>
<option value="19AAAAA">19AAAAA</option>
<option value="sdsdas">sdsdas</option>
<option value="dasdasdasd">dasdasdasd</option>
Simply flatten the multi-dimensional array, and then loop through it.
Suppose $arr in your original multi-dimensional array
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
foreach($it as $value){
?>
<option value="<?php echo $value; ?>"><?php echo $value; ?></option>
<?php
}
Here are the relevant references:
http://php.net/manual/en/class.recursiveiteratoriterator.php
http://php.net/manual/en/class.recursivearrayiterator.php
<?php
foreach($arr as $val){
foreach($val as $val2){
foreach($val2 as $val3){ ?>
<option value="<?php echo $val3;?>"><?php echo $val3 ;?></option><?php
}
}
}
?>
You need to flat array. You can do it with recursive function. Here you have general function for that.
/**
* Get multilevel array convert to single-level array
* #param $array
* #return array
*/
function getFlattened($array) {
$flattened = [];
foreach ($array as $flat) {
if (is_array($flat)) {
$flatArray = array_merge($flatArray, getFlattened($flat));
} else {
$flattened[] = $flat;
}
}
return $flattened;
}
Of course you can use that approach to recursively display select - not only to flat array.
<?php foreach($array as $inner): ?>
<?php foreach($inner as $innerTwo): ?>
<?php foreach($innerTwo as $item): ?>
<option value="<?= $item ?>"><?= $item ?></option>
<?php endforeach; ?>
<?php endforeach; ?>
<?php endforeach; ?>
you may try this.
<?php
$input = Array(
Array
(
0 => 7,
1 => 13000
),
Array
(
0 => '19AAAAA',
1 => 'sdsdas'
)
);
$options = "";
$result = call_user_func_array("array_merge", $input);
for($i = 0;$i< count($result);$i++ ){
$options .="<option value='".$result[$i]."'>".$result[$i]."</option>";
}
echo $options;

More than two variables in a foreach loop

I need some information regarding whether or not we can put more than two variable in a foreach loop. Do keep in mind I'm still a complete newbie :D
For example, I'm getting the data of the variable from a database with comma's
<?php
while($segment = $results->fetchRow()) {
$seg = explode(',', $segment['name']);
$section = explode(',', $segment['sek_id']);
$array = array_combine($seg, $section);
foreach($array as $out => $key){
if($out != ""){
?>
<option value="<?php echo $key; ?>"><?php echo $out; ?></option>
and here I managed to put two variables into my foreach loop.
Is there any way with it while still using a foreach loop? Like maybe if I have an 'id=""' where I would put the id's that is in comma's in it?
You can use following way.
<?php
$results = $results->fetchRow();
foreach($results as $result)
{
if(!empty($result['name']))
{
?>
<option value="<?php echo $result['sek_id']; ?>">
<?php echo $result['name']; ?>
</option>
<?php
}
}
<?php
That will be great if you can provide result of $results->fetchRow();
Let me know in case of any query.

Print out something only when value is within specific group during loop in PHP

I have a big array that is being used throughout the site and changing its structure just for the following task would be a pain. I want to make several select boxes with another array. The output I want to get is like this:
/* Example Array:
$allAnimals = array("Frogs","Toads","Bats","Elephants","Rats","Seals",
"Crocodilians","Turtles");
$group = array("Frogs"=>"Amphibian","Bats"=>"Mammal","Crocodilians"=>"Reptile");
*/
<select name='Amphibian'>
<option value='0'>Frogs</option>
<option value='1'>Toads</option>
</select>
<select name='Mammal'>
<option value='2'>Bats</option>
<option value='3'>Elephants</option>
<option value='4'>Rats</option>
<option value='5'>Seals</option>
</select>
<select name='Reptile'>
<option value='6'>Crocodilians</option>
<option value='7'>Turtles</option>
</select>
I can't figure out how to print out the options only when the value is within the specific animal group during each iteration of $group. I have tried each() to get the next animal $endAnimal from $group and then break the internal loop if $animal matches the $endAnimal, but I also need to make the loop start printing options at specific values.
<?php
$allAnimals = array("Frogs","Toads","Bats","Elephants","Rats","Seals","Crocodilians","Turtles");
$group = array("Frogs"=>"Amphibian","Bats"=>"Mammal","Crocodilians"=>"Reptile");
foreach($group as $thisAnimal=>$category){
$nextKey = (each($group));
$endAnimal = $nextKey['key'];
print "<select name='$category'>";
foreach($allAnimals as $idx=>$animal){
print "<option value='$idx'>$animal</option>";
if($endAnimal === $animal){
break;
}
}
print "</select>";
}
?>
Please check this out:-
<?php
$allAnimals = array("Frogs","Toads","Bats","Elephants","Rats","Seals","Crocodilians","Turtles");
$group = array("Frogs"=>"Amphibian","Bats"=>"Mammal","Crocodilians"=>"Reptile");
$group_keys = array_keys($group); // get the keys of group array
$j = 0;
foreach($group_keys as $key => $group_k){
print "<select name='$group[$group_k]'>";
if(isset($group_keys[$key+1])){
$new_value = $group_keys[$key+1];
}else{
$new_value = '';
}
if($new_value ==''){
foreach($allAnimals as $key => $allAnm){
print "<option value='$j'>$allAnm</option>";
unset($allAnimals[$key]);
$j ++;
}
}else{
$key_from = array_search($new_value,$allAnimals);
for($i = 0; $i<$key_from; $i++){
print "<option value='$j'>$allAnimals[$i]</option>";
unset($allAnimals[$i]);
$j ++;
}
}
$allAnimals = array_values($allAnimals);
print "</select>";
}
Output:- https://eval.in/379462 (eval.in)
local end :- (for better showing) :- http://prntscr.com/7fmtbi
Array of Array is the solution I think
$group = array( "Amphibian" => array("Frogs", "Toads"), "Mammal" => array("Bats", "Elephants", "Rats", "Seals"), "Reptile" => array("Crocodilians", "Turtles") );
foreach($group as $thisAnimal=>$category){
print "<select name='$category'>";
foreach($category as $idx=>$animal){
print "<option value='$idx'>$animal</option>";
}
print "</select>";
}
Thank you for your responses and answers. I just sort of get that to work by checking whether $thisAnimal from $group is the same as $animal from $allAnimals during the internal loop. If it's the same, turn $passThis to true and then proceed to print out the option until $endAnimal matches $animal. Example
<?php
$allAnimals = array("Frogs","Toads","Bats","Elephants","Rats","Seals","Crocodilians","Turtles");
$group = array("Frogs"=>"Amphibian","Bats"=>"Mammal","Crocodilians"=>"Reptile");
foreach($group as $thisAnimal=>$category){
$nextKey = (each($group));
$passThis = false;
$endAnimal = $nextKey['key'];
print "<select name='$category'>";
foreach($allAnimals as $idx=>$animal){
if($animal === $thisAnimal){
$passThis = true;
}
if($endAnimal === $animal){
break;
}
if($passThis === true)
{
print "<option value='$idx'>$animal</option>";
}
}
print "</select>";
}
?>

if else statement not work in option input

HERE is my code :
var $myarray =array ('black','blue','brown','yellow')
if ( $row['color']=="") {
echo"<option value='' selected>---select---</option>";
}
foreach ($myarray as $color) {
if ($row['color']!="" && $row['color']==$color) {
echo"<option value='$color' selected>$color</option>";
}else {
echo"<option value='$color'>$color</option>";
}
}
My question is how to get rid of the (<option value='' selected>---select---</option>)
if $row['color'] is not null or not empty?
I´ve tried many ways...but nothing helped. :S
<?php
$myarray =array ('black','blue','brown','yellow');
$row['color']='';
?>
<select name='whatever'>
<?php
if ($row['color']=='' || $row['color']==null){
echo "<option value=''>----Select----</option>";
}
foreach ($myarray as $color){
if ($row['color']==$color){
echo"<option value='$color' selected>$color</option>";
}
else{
echo"<option value='$color'>$color</option>";
}
}
?>
You declared the variable in the first line with var, which is not a part of PHP. You need to declare it like all your other variables, by putting a $ at the start of it. You also reference $mysrray instead of $myarray
Try this. it should work.
$myarray = array('black','blue','brown','yellow')
foreach ($myarray as $color) {
if ($row['color'] != "" && $row['color']==$color)
{
echo '<option value="'.$color.'" selected="selected">'.$color.'</option>';
}
elseif($row['color']=="")
{
echo '<option value="" selected="selected">---select---</option>';
}
}

PHP loop within a loop, option selected?

Using PHP I echo out table rows in a loop like this:
<?php
/* SQL STUFF */
while ($row = mysql_fetch_array($select_courseelements)) {
echo "<tr>\n";
echo "<td>".$row['scpe_name']."</td>\n";
echo "<td>".$row['scpe_days']."</td>\n";
echo "</tr>\n";
}
Now I would like to include a <select> element with 5 predefined <option> values inside a <td> running with the loop. The option values will be 1 to 5.
There is also a column inside the $row loop that holds a value of 1 to 5 ($row['scpe_grades_status']).
Each time this value is equal to the one in the <select> I want it to change it to selected='selected'.
Would this be possible?
My <select> will look something like this when it's being run in the loop:
echo "<td>\n";
echo "<select id='elements_grade'>\n";
echo "<option value='1'>Registrerad</option>\n";
echo "<option value='2'>Ej påbörjad</option>\n";
echo "<option value='3'>Pågående</option>\n";
echo "<option value='4'>Godkänd</option>\n";
echo "<option value='5'>Deltagit</option>\n";
echo "<option value='6'>Ej deltagit</option>\n";
echo "</select>\n";
echo "</td>\n";
Sure, build the values from a loop. and you can compare the values from that part.
for($i = 1; $i<=5; $i++) {
echo "<option value='$i'";
echo ($row['scpe_grades_status'] == $i) ? " selected='selected'": "";
echo ">...."</option>"
}
$array = array('Registrerad' => 1, 'Ej påbörjad' => 2, 'Pågående' => 3, 'Godkänd' => 4, 'Deltagit' => 5, 'Ej deltagit' => 6);
foreach ($array as $key=>$value) {
if ($value == $row['scpe_grades_status'])
echo '<option value="'.$value.'" selected>'.$key.'</option>';
else
echo '<option value="'.$value.'">'.$key.'</option>';
}
Something like that?

Categories