I have an array consisting of seat number in the following format
<?php
$seatnumbers = array(
"A1" => "1","A2" => "2",
"B1" => "3","B2" => "4","B3" => "5",
"C1" => "6","C2" => "7","C3" => "8",
"D1" => "9","D2" => "10","D3" => "11",
"E1" => "12","E2" => "13","E3" => "14"
);
?>
And also the retrieved data of reserved seats by users which comes in this format
<?php
$seat = array();
$sql = $db->query("SELECT booked_seat FROM mybooking where bus_id = '{$l}'");
$row = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach($row as $r){
$seat[] = $r['booked_seat'];
}
print_r($seat)
// Array ( [0] => A1 [1] => D2 )
?>
All I am trying to achieve is to disable the selected seats in a HTML select like I tried doing here
<?php
$keys = array_keys($seatnumbers);
$values = array_values($seatnumbers);
$skeys = array_keys($seat);
$val = array_values($seat);
for($i = 0; $i < 14; $i++ )
{
if($keys[$i] == $val[$i]){
echo "<option disabled>". $keys[$i]. "(Booked)</option>";
}else{
echo "<option value='".$keys[$i]."'>". $keys[$i]."-". $val[$i]. "(Available)</option>";
}
}
?>
But only the first option showed booked. How do compare for two arrays to disabled the reserved seats.
Here is the result of what I tried
Using prepared statements and also using PDO::FETCH_COLUMN to save having to process the result set from the SQL further. The code has comments to show how this is done.
You will have to change the output, but it matches what you have enough to modify it...
$query = "SELECT booked_seat FROM mybooking where bus_id = :busID";
$sql = $db->prepare($query);
$sql->execute(["busID" => $l]);
// Fetch an array with just the values of booked_seat
$seat=$sql->fetchAll(PDO::FETCH_COLUMN, 0);
// Flip array so the seat name becomes the key
$seat = array_flip($seat);
$seatnumbers = array(
"A1" => "1","A2" => "2",
"B1" => "3","B2" => "4","B3" => "5",
"C1" => "6","C2" => "7","C3" => "8",
"D1" => "9","D2" => "10","D3" => "11",
"E1" => "12","E2" => "13","E3" => "14"
);
foreach ( $seatnumbers as $seatName => $number ) {
echo $seatName;
// If the key is set in the seat array, then it is booked
if ( isset($seat[$seatName]) ){
echo " Seat booked".PHP_EOL;
}
else {
echo " Seat not booked".PHP_EOL;
}
}
This is a typical task for using foreach
<html>
<head></head>
<body>
<?php
$seatnumbers = array(
"A1" => "1","A2" => "2",
"B1" => "3","B2" => "4","B3" => "5",
"C1" => "6","C2" => "7","C3" => "8",
"D1" => "9","D2" => "10","D3" => "11",
"E1" => "12","E2" => "13","E3" => "14"
);
$seat = array(
"0" => "A1","1" => "D2",
"2" => "E1","3" => "E2","4" => "E3"
);
echo "<select>";
foreach ($seatnumbers as $ikey=>$ivalue)
{
if(in_array($ikey,$seat)){
echo "<option disabled>". $ikey. "(Booked)</option>";
}else{
echo "<option value='".$keys[$i]."'>". $ikey."-". $val[$i]. "(Available)</option>";
}
}
echo "</select>";
?>
</body>
</html>
Related
I have the following 2D array and I would like to get the key of the smalest value in the [0] column if done is equal to no
$graph= array(
"CityA" => array(
"0" => "1",
"1" => "CityC",
"done" => "no",
),
"CityB" => array(
"0" => "4",
"1" => "CityA",
"done" => "no",
),
"CityC" => array(
"0" => "5",
"1" => "CityA",
"done" => "no",
),
);
Try this,
$arr = array_map(function($v){return $v[0];}, $graph);
$key = array_keys($arr, min($arr));
Here you go.
$tes = min( array_column( $graph, 0 ) );
$key = array_search( $tes, array_column( $graph, 0 ) );
$array_keys = array_keys($graph);
echo $array_keys[$key];
You should perform all of your checks in a single pass through your array.
My snippet will provide the first qualifying (contains the lowest [0] value AND has a done value of no) row's key.
Code: (Demo)
$graph = [
"CityB" => ["0" => "1", "1" => "CityA", "done" => "no"],
"CityA" => ["0" => "1", "1" => "CityC", "done" => "no"],
"CityD" => ["0" => "1", "1" => "CityD", "done" => "yes"],
"CityC" => ["0" => "5", "1" => "CityA", "done" => "no"]
];
$result = [];
foreach ($graph as $key => $row) {
if ($row['done'] === 'no' && (!isset($result[$key]) || $row[0] < $result[$key])) {
$result[$key] = $row[0];
}
}
echo key($result) ?? 'No "done => no" rows';
Output:
CityB
I would like to echo a bunch of arrays in numerical order, I tried using WHILE method but lacks the knowledge on how to combine strings to call a variable and get the value inside the array.
$ins1 = array (
"select" => array (
"1" => "1"
),
"note" => array (
"1" => "Message"
)
);
$ins2 = array (
"select" => array (
"1" => "2"
),
"note" => array (
"1" => "Sorry"
)
);
$count = 1;
while($count <= 2){
$ins = '$ins'.$count;
echo $ins["select"][$count] .' '. $ins["note"][$count].'<br>';
$count++;
}
OUTPUT SHOULD BE:
1 Message
2 Sorry
What you're looking for is "Variable variables", through which you can set the variable name dynamically; so to get what you want, change your code as the following:
$count = 1;
while($count <= 2){
$ins = 'ins'.$count;
$var = $$ins; // now your $var is either $ins1 or $ins2 :)
echo $var["select"][1] .' '. $var["note"][1].'<br>';
$count++;
}
The output would be:
1 Message
2 Sorry
You should have combined the two variable, and make life easier:
$ins = [
[//$ins1
"select" => array ("1" => "1"),
"note" => array ("1" => "Message" )
],
[//$ins2
"select" => array ("1" => "2"),
"note" => array ("1" => "Sorry")
]
];
for ($i = 0; $i < count($ins); $i++)
{
echo $ins[$i]["select"][1]." ".$ins[$i]["note"][1]."<br/>";
}
for dynamic name of variables, see other answers.. hope i've helped you.. Cheers! ;)
this will do the trick for you:
$ins1 = array (
"select" => array (
"1" => "1"
),
"note" => array (
"1" => "Message"
)
);
$ins2 = array (
"select" => array (
"1" => "2"
),
"note" => array (
"1" => "Sorry"
)
);
for($i=1; $i<1000; $i++) {
$arr_name = 'ins'.$i;
if(isset($$arr_name)) {
$str = '';
foreach ($$arr_name as $key => $value) {
$str .= $value[1].' ';
}
echo trim($str).'<br/>';
} else {
break;
}
}
Note: I have taken 1000 as a highest possible value, you can change accordingly. like in your case it is 2.
I have a drop down menu on my site where I want all US states listed. I have an array of states but I can't seem to get ALL of them to load into my <option> tag. Below is the first 15 states as an array and my <select> code. Eventually the drop down will link to separate pages for each state with an image of that state (that is why I have an "img" within each state array). The only states I get to load in the drop down are: Alaska, Arkansas, Colorado, Delaware, Florida, Hawaii, and Illinois.
<?php
$states = array();
$states['AL'] = array (
"name" => "Alabama",
"img" => "http://getwidgetsfree.com/images/state_png/al.png"
);
$states['AK'] = array (
"name" => "Alaska",
"img" => "http://getwidgetsfree.com/images/state_png/ak.png"
);
$states['AZ'] = array (
"name" => "Arizona",
"img" => "http://getwidgetsfree.com/images/state_png/az.png"
);
$states['AR'] = array (
"name" => "Arkansas",
"img" => "http://getwidgetsfree.com/images/state_png/ar.png"
);
$states['CA'] = array (
"name" => "California",
"img" => "http://getwidgetsfree.com/images/state_png/ca.png"
);
$states['CO'] = array (
"name" => "Colorado",
"img" => "http://getwidgetsfree.com/images/state_png/co.png"
);
$states['CT'] = array (
"name" => "Connecticut",
"img" => "http://getwidgetsfree.com/images/state_png/ct.png"
);
$states['DE'] = array (
"name" => "Delaware",
"img" => "http://getwidgetsfree.com/images/state_png/de.png"
);
$states['DC'] = array (
"name" => "District of Columbia",
"img" => "http://pharmacoding.com/dendreon/provenge/images/dc.png"
);
$states['FL'] = array (
"name" => "Florida",
"img" => "http://getwidgetsfree.com/images/state_png/fl.png"
);
$states['GA'] = array (
"name" => "Georgia",
"img" => "http://getwidgetsfree.com/images/state_png/ga.png"
);
$states['HI'] = array (
"name" => "Hawaii",
"img" => "http://getwidgetsfree.com/images/state_png/hi.png"
);
$states['ID'] = array (
"name" => "Idaho",
"img" => "http://getwidgetsfree.com/images/state_png/id.png"
);
$states['IL'] = array (
"name" => "Illinois",
"img" => "http://getwidgetsfree.com/images/state_png/il.png"
);
$states['IN'] = array (
"name" => "Indiana",
"img" => "http://getwidgetsfree.com/images/state_png/in.png"
);
?>
<select>
<?php
foreach($states as $state) {
echo "<option value='state.php?id=" . $state["id"] . ">" . $state["name"] . "</option>";
};
?>
</select>
You are missing a closing ``' quote, next to the option tag’s closing bracket right after $state["id"].
<?php
foreach($states as $state) {
echo "<option value='state.php?id=" . $state["id"] . "'>" . $state["name"] . "</option>";
};
?>
To answer the most immediate question, you are missing a closing quote when you set <option>. Then you are setting $state["id"] when that key doesn’t exist in the structure you have. You should be using the actual key in that array.
So with that in mind, here is my re-factored version of the code. Note you can use string substitution with double quotes (") so no need for concatenation. Which makes this easier to read and debug as well.
echo '<select>';
foreach($states as $state_key => $state_value) {
echo "<option value='state.php?id=$state_key'>"
. $state_value["name"]
. "</option>"
;
};
echo '</select>';
That said, you can simplify your code by using an array like this:
$states = array();
$states['al'] = array('name' => 'Alabama');
$states['ak'] = array('name' => 'Alaska');
$states['az'] = array('name' => 'Arizona');
$states['ar'] = array('name' => 'Arkansas');
$states['ca'] = array('name' => 'California');
$states['co'] = array('name' => 'Colorado');
$states['ct'] = array('name' => 'Connecticut');
$states['de'] = array('name' => 'Delaware');
$states['de'] = array('name' => 'Delaware');
$states['dc'] = array('name' => 'District of Columbia');
$states['fl'] = array('name' => 'Florida');
$states['ga'] = array('name' => 'Georgia');
$states['hi'] = array('name' => 'Hawaii');
$states['id'] = array('name' => 'Idaho');
$states['il'] = array('name' => 'Illinois');
$states['in'] = array('name' => 'Indiana');
echo '<select>';
foreach($states as $state_key => $state_value) {
$states[$state_key] = array_merge($states[$state_key], array('img' => "http://getwidgetsfree.com/images/state_png/$state_key.png"));
$state_key_uc = strtoupper($state_key);
echo "<option value='state.php?id=$state_key_uc'>"
. $state_value['name']
. "</option>"
;
};
echo '</select>';
The goal is you are starting out with a basic array that has the lowercase state code for the array key. Then set the name as you did before. But when you do the foreach loop, then you just set the img value & merge that using array_merge into the existing array.
I have the following code. Basically I want to search through the keys of this multidimensional array from top to bottom, but ignore the sub-array with the key specified by $ignoreKey. As you can see by the "array_key_exists" logic, it is currently built for a 1D array.. I tried some examples but having problems (so have left my 1D code as is below).
If all went as planned, I would have "thirtyfromgroup1" echoed.
What would I have to change in the following to achieve this?
$keyCheck = "30";
$ignoreKey = "group2";
if (array_key_exists($keyCheck, $topLevel)) {
echo $topLevel[$keyCheck];
}
$topLevel = array(
"group1" => array
(
"12" => "twelve",
"30" => "thirtyfromgroup1"
),
"group2" => array
(
"14" => "fourteen",
"30" => "thirty"
),
"group3" => array
(
"12" => "twelve",
"26" => "thirty"
),
);
Assuming you just want to ignore keys in the top level of your array, and are just searching the keys in the second level:
$keyCheck = "30";
$ignoreKey = "group2";
$topLevel = array(
"group1" => array(
"12" => "twelve",
"30" => "thirtyfromgroup1"
),
"group2" => array(
"14" => "fourteen",
"30" => "thirty"
),
"group3" => array(
"12" => "twelve",
"26" => "thirty"
),
);
foreach($topLevel as $topKey => $topValue)
{
if ($topKey == $ignoreKey)
continue;
foreach($topValue as $subKey => $subValue)
{
if ($subKey == $keyCheck)
echo $subValue;
}
/* Alternatively:
if (isset($topValue[$keyCheck]))
echo $topValue[$keyCheck];
*/
}
I am trying to creates the array dynamically like below using php
$data = array(
array("date" => "1/2/2012", "sentstatus" => "0", "mobile" => "14578998"),
array("date" => "21/2/2012", "sentstatus" => "1", "mobile" => "14668998"),
array("date" => "1/5/2012", "sentstatus" => "1", "mobile" => "14598998"),
array("date" => "1/6/2012", "sentstatus" => "0", "mobile" => "14578748"),
);
Below is my PHP code that insert the sql server data into array but the problem is that it the array is formed of only last result set row of the database table. I am not getting the idea to insert all database table row into array as shown above:
$sql = "SELECT [start_date_time],[sent_status],[mobile_number] ,[play_file]
FROM [slice].[dbo].[tbl_message_detail] ";
$res = odbc_exec($con,$sql) or die(odbc_error());
$rows = odbc_num_rows($res);
while($row = odbc_fetch_array($res))
{
$data = array(
array("Date_Time" => $row['start_date_time'], "Send_Status" => $row['sent_status'], "Mobile_Number" => $row['mobile_number'], "play_file" => $row['play_file'])
);
}
You are getting only the last row because you are creating a new array with every iteration. Declare $data outside of the while loop.
try this code:
while($row = odbc_fetch_array($res))
{
$data[] = array("Date_Time" => $row['start_date_time'],
"Send_Status" => $row['sent_status'],
"Mobile_Number" => $row['mobile_number'],
"play_file" => $row['play_file']);
}
You're overwriting the $data variable at each round of the loop. This:
$data = array();
while($row = odbc_fetch_array($res))
{
$data[] = array("Date_Time" => $row['start_date_time'],
"Send_Status" => $row['sent_status'],
"Mobile_Number" => $row['mobile_number'],
"play_file" => $row['play_file']
);
}
should work as you need