Return first key in foreach - php

I have problem in returning the first key of array in foreach. I can return the $key but i cant figure out on returning the first $key only.
<td>
<div align="center">
<span class="formlist">
<select id="plant" name="plant[]" class="form-control" multiple="multiple">
<?php
$query_plant = "SELECT * FROM plant WHERE plant_enable=1 ORDER BY plant_name";
$rs_plant = DB_Query($query_plant);
while ($row_plant = DB_FetchRow($rs_plant)) {
$plant.='<option name='.$row_plant["plant_shortname"].' value='.$row_plant["plant_id"].'>' .$row_plant["plant_name"].' ['.$row_plant["plant_id"].']</option>';
}
mysql_free_result($rs_plant);
echo $plant;
?>
</select>
</span>
</div>
</td>
if(isset($_POST['plant'])) {
$checkbox1 = $_POST['plant'];
$chk="";
$stf_sql = "SELECT * FROM test_plant WHERE staff_id = '".$STAFF_ID."'";
$stf_res = DB_Query($stf_sql);
if(DB_RowsReturned($stf_res) > 0) {
$del_sql = "DELETE FROM test_plant WHERE staff_id = '".$STAFF_ID."'";
$del_res = DB_Query($del_sql);
}
foreach($checkbox1 as $chk1)
{
$in_ch="insert into test_plant(staff_id, plant_name, submit_dt) values ('$STAFF_ID','$chk1', Now())";
$in_res = DB_Query($in_ch);
$abc = mysql_query("SELECT * FROM test_plant");
while($abc_row = mysql_fetch_assoc($abc)) {
foreach($abc_row as $key => $value) {
echo $key; //return first key here
}
}
}
} else {
echo "OK";
}
I have tried returning $key[0] but it returns the first letter only. I want to return 'p_id'

Like this,
$keys = array_keys($checkbox1);
print_r($keys); // for all keys
echo $keys[0]; // It will echo first key of the array.

You could reset the internal array pointer and then get the key of the current element:
reset($checkbox1);
echo key($checkbox1);
(Put this outside your outermost while loop).
Or you could even get all the array keys, and then grab the current key:
echo current(array_keys($checkbox1));

Related

Add/get data to/from two Dimensional array Doesn't work

I'm trying to add data from database to 2-dimensional array and then unpacking.
This function is in a folder named imsConnection.php
function getCurrency() {
global $cn;
$sql = "select * from Currency";
$res = mysqli_query($cn, $sql);
$a = array();
if (mysqli_num_rows($res) > 0) {
while ($row = mysqli_fetch_array($res)) {
$a[] = array($row['currencyID'], $row['currencyName']);
}
}
return $a;
}
And to unpack it into drop box:
<select name="drpCurrency" required>
<?php
require_once("imsConnection.php");
$a = getCurrency();
foreach($a as $i) {
echo "<option value='$i'>$a[$i]</option>";
}
?>
</select>
To make a formal answer: If you create multi dimentaion array and you loop with foreach you need to echo the value according the key you need. In you case:
foreach($a as $i)
echo "<option value='" . $i["currencyID"] ."'>" . $i['currencyName'] . "</option>";
I recommend you change your array do be according key - change the getCurrency function as:
while($row = mysqli_fetch_array($res)){
$a[$row['currencyID']] = $row['currencyName'];
Then you can use it as:
$a = getCurrency();
foreach($a as $k => $i)
echo "<option value='$k'>$i/option>";
Assuming you want the value as currency ID and the option content as the currency name

Why I can't access the array element using it's key?

I have a bellow php while and for loop.
In while loop it's storing $ch_for data in $ch_for array.
Using print_r this array is showing these value :
Array ( [ch7] => Seven [ch8] => Eight )
And trying to access this array data in for loop using this line :
echo $ch_for["ch{$x}"];
But it's showing an error message : Illegal string offset 'ch7' in
...
While and For Loop
$ch_for = array();
$ch_name = array();
while ( $fetchChannel = mysqli_fetch_array($getChannel) ) {
$ch_id = (int) $fetchChannel['ch_id'];
$ch_for[$fetchChannel['ch_name']] = htmlspecialchars($fetchChannel['ch_for']);
$ch_name[] = htmlspecialchars($fetchChannel['ch_name']);
}
for ($x=1; $x<=12; $x++) {
if( in_array('ch'.$x, $ch_name)) {
$sel = 'checked = "checked" ';
echo $ch_for["ch{$x}"];
} else {
$sel = '';
$ch_for = '';
}
?>
<div class="checkbox form-inline">
<label><input <?php echo $sel; ?> type="checkbox" name="ch_name[]" value="ch<?php echo $x; ?>">CH<?php echo $x; ?></label>
<input type="text" name="ch_for[]" value="<?php echo $ch_for; ?>" placeholder="Channel details" class="form-control ch_for">
</div>
<?php
}
Result of var_dump(array_keys($ch_for));
array(2) {
[0]=>
string(3) "ch7"
[1]=>
string(3) "ch8"
}
Your array is associative array.SO use in_array() in array_keys.Like this..
<?php
$array = array('ch7'=>'Seven','ch8'=>'Eight');
$keys = array_keys($array);
//print_r($keys);
for ($x=1; $x<=12; $x++) {
if( in_array('ch'.$x,$keys)) {
$sel = 'checked = "checked" ';
echo $array["ch{$x}"].PHP_EOL;
} else {
$sel = '';
$ch_for = '';
}
}
?>
Output:
Seven
Eight
You're overwriting $ch_for in your else-branch since the first key is ch7, hence the first loop (ch1 is not in $ch_name and thus triggers the else) overwrites $ch_for.

How to select values where another value is an array?

I'm trying to select values where another POST values are an array, I do not know what is wrong with my query giving me this error. I'm trying to know what courses are just added to table. I have five inputs in the form.
Notice: Trying to get property of non-object in C:\Apache\htdocs\xxx\addcourse.php on line 262
Here is my code
<?php
if(isset($_POST['Submit'])) {
$code= isset($_POST['code']) ? $_POST['code'] : '';
$coursecode = isset($_POST['coursecode']) ? $_POST['coursecode'] : '';
$both=$code[$x] .' '. $coursecode[$x];
$sqlcourses = "SELECT * FROM courses where course_code='$both' ORDER BY course_id DESC LIMIT 5 ";
$resultcourses = $mysqli->query($sqlcourses);
if ($resultcourses->num_rows > 0) {
while($row = $resultcourses->fetch_assoc()) {
?>
</p>
<p> </p>
<p> </p>
<table width="415" border="0">
<tr>
<?php
$courses=$row["course_code"];
echo $courses;
?>
</div>
</tr>
</table>
<?php
}
}
}
?>
First, you build an array of the course codes that you want to retrieve; I'm leaving off the boundary checks for simplicity:
$codes = [];
foreach ($_POST['code'] as $k => $code) {
$codes[] = $code . ' ' . $_POST['coursecode'][$k];
}
Then, you prepare the statement you will use:
$stmt = $mysqli->prepare("SELECT *
FROM courses
WHERE course_code = ?
ORDER BY course_id DESC
LIMIT 5");
Followed by the main loop:
foreach ($codes as $code) {
$stmt->bind_param('s', $code);
assert($stmt->execute());
$res = $stmt->get_result();
while ($row = $res->fetch_assoc()) {
// ...
}
}
you can try this way with small modified code
first you have to convert string to array to get index (x) in array
$code = explode(" ", $code);
$course = explode(" ", $coursecode);
foreach ($code as $cd => $x) {
$both = $code[$x].' '.$coursecode[$x];
$sqlcourses = "SELECT * FROM courses where course_code='$both' ORDER BY course_id DESC LIMIT 5 ";
$resultcourses = $mysqli->query($sqlcourses);
}
second you can choose variable $code or $course as length of loop based on your case
foreach ($course as $crs => $x) {
your condition...
}

How to display values from two separate tables from mySQL database?

I am trying to view values from two separate tables using a foreach loop. The user chooses a "Start semester" and an "End semester" from a drop down list, and those two semesters are stored into an array called $semesterarray
<table style='width: 75%; text-align: left;' cellpadding = '4'>
<tr bgcolor=#000090>
<th><FONT COLOR = #FFFFFF><b><?php echo $startsem ?></b></th>
<th><FONT COLOR = #FFFFFF><b><?php echo $endsem ?></b></th>
</tr>
// If $semesterarray contains 10 and 11, I want to be able to view the
// courses taken in the 10 semester and the 11 semester under two separate columns.
<?php
function getSemesterDetails($semester)
{
$output = "";
$semA = $semester."reg";
$query = "SELECT course1,course2,course3 FROM $semA";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
// row displays: [course1]=> [course2]=> [course3]=>
// Add semester code to array Keys to indicate proper semester
// [course1.11]=> [course2.11]=> [course3.11]=>
foreach ($row as $key => $value)
{
$row[$key.".".$semester] = $value;
unset($row[$key]);
}
$startcourse1 = $row['course1.'.$semester];
$startcourse2 = $row['course2.'.$semester];
$startcourse3 = $row['course3.'.$semester];
$startcoursesarray = array($startcourse1, $startcourse2, $startcourse3);
$startcourses = implode("<br>", $startcoursesarray);
$endcourse1 = $row['course1.'.$semester];
$endcourse2 = $row['course2.'.$semester];
$endcourse3 = $row['course3.'.$semester];
$endcoursesarray = array($endcourse1, $endcourse2, $endcourse3);
$endcourses = implode("<br>", $endcoursesarray);
echo "<tr bgcolor=#ABB5F6>
<td>$startcourses</td>
<td>$endcourses</td>
</tr>";
}
}
foreach ($midsemarrayA as $key => $semester)
{
echo getSemesterDetails($semA);
}
?>
Any ideas?
This should be enough for you to make a start:
function getSemesterDetails ($semester) {
$output = "";
$query = "SELECT course1,course2,course3 FROM $semester";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
// row displays: [course1]=> [course2]=> [course3]=>
// Add semester code to array Keys to indicate proper semester
// [course1.11]=> [course2.11]=> [course3.11]=>
foreach ($row as $key => $value) {
$row[$key.".".$semester] = $value;
unset($row[$key]);
}
$startcourse1 = $row['course1.'.$semester];
$startcourse2 = $row['course2.'.$semester];
$startcourse3 = $row['course3.'.$semester];
$startcoursesarray = array($startcourse1, $startcourse2, $startcourse3);
$startcourses = implode("<br>", $startcoursesarray);
$endcourse1 = $row['course1.'.$semester];
$endcourse2 = $row['course2.'.$semester];
$endcourse3 = $row['course3.'.$semester];
$endcoursesarray = array($endcourse1, $endcourse2, $endcourse3);
$endcourses = implode("<br>", $endcoursesarray);
$output .= "<tr bgcolor=#ABB5F6>
<td>$startcourses</td>
<td>$endcourses</td>
</tr>";
}
return $output;
}
foreach ($semesterarray as $key => $semester) {
getSemesterDetails($semester);
}
You'll want to get it to return an array of values rather than a string, but shifting it into a subroutine should do the trick.

Sorting text data by number value

I have mock fantasy football form that creates data in an external text file and I have everything working, I have just run into one problem. Can someone show me how I can sort the players by their number (largest on top) and then highlight (in red) the whole row of the player that has had the most points?
Here is my form file:
<!doctype html public "-//W3C//DTD HTML 4.0 //EN">
<html>
<head>
<title>Fantasy Football</title>
</head>
<body>
<form action="team.php" method="POST">
<table border="1">
<tr><td>Player Name</td><td><input type="text" name="name"</td></tr>
<tr><td>Position</td><td><input type="text" name="position"</td></tr>
<tr><td>Number</td><td><input type="text" name="number"</td></tr>
<tr><td>Team</td><td><input type="text" name="team"</td></tr>
<tr><td>Points per game</td><td><input type="text" name="points"</td></tr>
<tr><td colspan="2" align="center"><input type="submit"></td></tr>
</table>
</form>
</body>
</html>
And here is the return data:
<?php
$name = $_POST['name'];
$team = $_POST['team'];
$number = $_POST['number'];
$position = $_POST['position'];
$points = $_POST['points'];
$DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
# $fp = fopen("$DOC_ROOT/../php/football.txt","ab");
if(!$fp) {
echo 'Error: Cannot open file.';
exit;
}
fwrite($fp, $name."|".$team."|".$number."|".$position."|".$points."\n");
?>
<?php
$DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
$players = file("$DOC_ROOT/../php/football.txt");
echo "<table border='2'>";
echo "<tr> <td>Name</td> <td>Team</td> <td>number</td> <td>Position</td> <td>Points</td> </tr>";
for($i = 0; $i < sizeof($players); $i++) {
list($name,$team,$number,$position,$points) = explode('|', $players[$i]);
echo '<tr><td>'.$name.'</td><td>'.$team.'</td><td>'.$number.'</td>
<td>'.$position.'</td><td>'.$points.'</td></tr>';
}
echo '</table>';
?>
Not really good at inserting bits an pieces of code, so if you could, can you tell me exactly where to put whatever you can give me?
Update:
Is this where I needed to put everything? The way it is now, when I submit my form I don't see anything! Obviously I did something wrong, so I'm open to suggestions!
<?php
function sort_player_array( $array, $key, $asc = true) {
$result = array();
$values = array();
foreach ($array as $id => $value) {
$values[$id] = isset($value[$key]) ? $value[$key] : '';
}
if ($asc) {
asort($values);
}
else {
arsort($values);
}
foreach ($values as $key => $value) {
$result[$key] = $array[$key];
}
return $result;
}
?>
<?php
$name = $_POST['name'];
$team = $_POST['team'];
$number = $_POST['number'];
$position = $_POST['position'];
$points = $_POST['points'];
$DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
# $fp = fopen("$DOC_ROOT/../php/football.txt","ab");
if(!$fp) {
echo 'Error: Cannot open file.';
exit;
}
?>
<?php
fwrite($fp, $name."|".$team."|".$number."|".$position."|".$points."\n");
$players = file("$DOC_ROOT/../php/football.txt");
$player_array = array();
foreach($players AS $player)
{
list($name,$team,$number,$position,$points) = explode('|', $players[$i]);
$player_array[] = array('name' => $name,
'number' => $number,
'position' => $position,
'points' => $points,
);
}
$sorted_players = sort_player_array($player_array, 'number', true);
foreach( $sorted_players AS $player )
{
echo '<tr><td>'.$player[name].'</td><td>'.$player[team].'</td><td>'
.$player[number].'</td><td>'.$player[position].'</td><td>'.$player[points].'</td></tr>';
} ?>
first of all you are programming in PHP, use COUNT() instead of SIZEOF().
sizeof() is an alias of count() and might be removed as php evolves.
We need a function for sorting the array:
function sort_player_array( $array, $key, $asc = true) {
$result = array();
$values = array();
foreach ($array as $id => $value) {
$values[$id] = isset($value[$key]) ? $value[$key] : '';
}
if ($asc) {
asort($values);
}
else {
arsort($values);
}
foreach ($values as $key => $value) {
$result[$key] = $array[$key];
}
return $result;
}
next build an array with php holding your data, then sort it .
$players = file("$DOC_ROOT/../php/football.txt");
$player_array = array();
foreach($players AS $player)
{
list($name,$team,$number,$position,$points) = explode('|', $players[$i]);
$player_array[] = array('name' => $name,
'number' => $number,
'position' => $position,
'points' => $points,
);
}
We sort the array as you requested by number, but any key is possible. also you can set ASC or DESC with the third variable
$sorted_players = sort_player_array($player_array, 'number', true);
foreach( $sorted_players AS $player )
{
echo '<tr><td>'.$player[name].'</td><td>'.$player[team].'</td><td>'.$player[number].'</td><td>'.$player[position].'</td><td>'.$player[points].'</td></tr>';
}
Seems like you need some kind of sorting algorithm function for $players. There are different kinds, and you can find many by googling "sorting algorithms", or you can write one yourself if you feel like "reinventing the wheel". Doing one yourself does make for good practice/fun :D
Here's a link to a wiki on bubble sort, probably the most common basic sorting and would help in your situation.
Prepare an array $playerData, which contains all player records and use their numbers as key. Then use ksort():
ksort( $playerData );
While preparing the $playerData, keep a variable $maxPoints and $mapPointsPlayerNumber and check each player's data against these values. Update them if current player's point is higher than $maxPoints.
I think you should be able to create arrays with the list function. Something like this:
//set array variables
for($i = 0; $i < sizeof($players); $i++) {
list($name[],$team[],$number[],$position[],$points[]) = explode('|', $players[$i]);
}
//sort all arrays by the number, in descending order
array_multisort($number, $position, $name, $team, $points, SORT_DESC);
//set the highest points to mostPoints variable
var mostPoints = max($points);
//Output table rows
for($i = 0; $i < sizeof($players); $i++) {
if($points[$i]==mostPoints){
//red background
echo '<tr style="background:#F44">';
}else{
echo '<tr>';
}
echo '<td>'.$name[$i].'</td><td>'.$team[$i].'</td><td>'.$number[$i].'</td><td>'.$position[$i].'</td><td>'.$points[$i].'</td></tr>';
}
I haven't tested this, so there may be a few things in there that I've missed, but it should work. See Array Multisort, and max functions. It may be better to assign a class to the red table row, instead of a style; that way you can alter the td tags; I think that's more browser-friendly. The CSS for that would be something like .redRow td {background:#F44} if you gave the tr the redRow class.

Categories