Hy,
how I retrieve information from an associative array like list in php.
var_dump shows something like this:
array(2) { [1]=> string(1) "1"
[2]=> string(1) "2" }
array(2) { [1]=> string(15) "gica_craioveanu"
[2]=> string(14) "alexandra_minu" }
array(2) { [0]=> string(10) "craiovaMAX"
[1]=> string(10) "alexMinu10" }
First array containd the id's, second the user name and third the passwords.
My attempt:
foreach ($row as $i => $id,$user_name,$user_pass) {
echo "<tr>\n" .
" <td>".var_dump($id)."</td>\n".
" <td>".var_dump($user_name)."</td>\n".
" <td>".var_dump($user_pass)."</td>\n".
" </tr>\n"
}
one of php file contains the script to construct the list:
while($row = mysqli_fetch_row($result))
{
/*$id[]=$row['user_id'];
$user_name[]=$row['user_name'];
$user_pass[]=$row['user_pass'];
$i=$i+1;*/
list($id[$i],$user_name[$i],$user_pass[$i++])=$row;
}
/*for($no=0; $no<$i; $no++){
echo $row[$i]."/".$row[$i]."/";
}*/
include 'user.html.php';
}
?>
and the user.html.php
to view the rows:
<?php
// while (list($id, $user_name, $user_pass)= each($row)) {
foreach($row as $i => $id,$user_name,$user_pass){
echo " <tr>\n" .
" <td>".$id."</td>\n".
" <td>".$user_name."</td>\n".
" <td>".$user_pass."</td>\n".
" </tr>\n";
/*echo "<tr>\n" .
" <td>".var_dump($id)."</td>\n".
" <td>".var_dump($user_name)."</td>\n".
" <td>".var_dump($user_pass)."</td>\n".
" </tr>\n"
*/
/*for($no=0; $no<$i; $no++){
echo "<tr>".
"<td>".$row[$i]."</td>".
"<td>".$row[$i]."</td>".
"<td>".$row[$i]."</td>".
"</tr>";*/
}
?>
while($row = mysqli_fetch_row($result)) {
list($id[$i],$user_name[$i],$user_pass[$i++])=$row;
}
...
for($i = 1; $i < count($id) + 1; $i++) {
echo " <tr>\n" .
" <td>".$id[$i]."</td>\n".
" <td>".$user_name[$i]."</td>\n".
" <td>".$user_pass[($i - 1)]."</td>\n".
" </tr>\n";
}
$id = array("1", "2");
$user_name = array("gica_craioveanu", "alexandra_minu");
$user_pass = array("craiovaMAX", "alexMinu10");
We presume that 3 arrays are always the same size :
// You make a loop on first array
for ( $i = 0 ; $i < count($id) ; $i++ )
{
// You use index $i to access to 3 arrays.
echo 'ID: '.$id[$i].'<br />';
echo 'Name: '.$user_name[$i].'<br />';
echo 'Password: '.$user_pass[$i].'<br />';
}
for($no=1; $no<$i+1; $no++)
{
echo "<tr>".
"<td>".$id[$no]."</td>".
"<td>".$user_name[$no]."</td>".
"<td>".$user_pass[($no-1)]."</td>".
"</tr>";
}
Inspired by Typoheads
Related
I have an array list that I wish to implode as I want to display each array with indexing to target that element. I'm trying but it is not displaying correctly. What am I doing wrong?
<?php
/*
var_dump($names); // below
array(4) {
[0]=>
string(22) "David Kaul"
[1]=>
string(23) "Julius Kaul"
[2]=>
string(22) "Robert Kaul"
[3]=>
string(22) "Juohn Kaul"
} */
for ($i = 0; $i <= 10; $i+=1) {
echo '<li class="item-' . $i . '">' . implode('</li><li class="item-'.$i.'">', $names) . '</li>';
}
?>
I think you just want a simple foreach over the $names array:
$names = array("David Kaul","Julius Kaul","Robert Kaul","Juohn Kaul");
foreach ($names as $i => $name) {
echo '<li class="item-' . $i . '">' . $name. '</li>' . "\n";
}
Output:
<li class="item-0">David Kaul</li>
<li class="item-1">Julius Kaul</li>
<li class="item-2">Robert Kaul</li>
<li class="item-3">Juohn Kaul</li>
Demo on 3v4l.org
I have an array of arrays and accessing the data is fine, but when I try to create separate tables based on a key, which is set to the numeric month that the data pulled from the database falls under.
I have:
array(1) {
[5]=>
array(12) {
["ID"]=>
string(5) "1001"
["created_timestamp"]=>
string(26) "2015-06-11 19:10:00"
["firstname"]=>
string(4) "John"
["lastname"]=>
string(3) "Doe"
}
}
array(1) {
[5]=>
array(12) {
["ID"]=>
string(5) "1002"
["created_timestamp"]=>
string(26) "2015-06-12 19:10:00"
["firstname"]=>
string(4) "Jane"
["lastname"]=>
string(3) "Doe"
}
}
array(1) {
[6]=>
array(12) {
["ID"]=>
string(5) "1003"
["created_timestamp"]=>
string(26) "2015-07-16 19:20:00"
["firstname"]=>
string(4) "John"
["lastname"]=>
string(4) "John"
}
}
The [5] Represents the current month -1. What I want to do is create a table and headers but only once, then populate the table with first and last name.
foreach($m as $key => $value)
{
if(key($m) != $currentKey)
{
$currentKey = key($m);
}
if($key == date("n", strtotime($value['created_timestamp']))-1);
{
for($i=$currentKey; $i<=$lastkey; $i++) {
echo "<br>".count($key);
$table .= '<table id=' . date("F-Y", strtotime($m[$currentKey]['created_timestamp'])) . ' class="tblclass">
<thead><tr><th>Month</th><th>ID</th><th>Customer</th></tr></thead>';
$table .= '<tbody>';
$table .= '<tr><td>'.date("F Y", strtotime($m[$currentKey]['created_timestamp'])).'</td><td>' . $value['ID'] . '</td><td>' . $value['lastname'] . ' ' . $value['firstname'] . '</td></tr>';
$table .= '</tbody>';
$table .= '</table>';
}
}
}
Whenever I run the code it creates a table for each separate array. I want to create one table for each separate month and populate it with anything with the same key. I feel like I'm missing something though. Any help would be greatly appreciated!
A dirty solution. Since info is lacking
Here are a few assumptions:
- Array is sorted in ASC order
- There is only one item in each array [ID, Name, Timestamp]
- IF there are more items, then you can just add a loop in there
- $m is the multi-dimensional array.
NOTE: Not tested.
$currentKey = 0;
$count= 0;
$lastKey = count($m) - 1;
foreach($m as $key => $value) {
if(key($m) != $currentKey) {
$currentKey = key($m);
if($count== 0) {
echo "<br>".count($key);
$table .= '<table id=' . date("F-Y", strtotime($m[$currentKey]['created_timestamp'])) . ' class="tblclass">
<thead><tr><th>Month</th><th>ID</th><th>Customer</th></tr></thead>';
$table .= '<tbody>';
} else {
$table .= '</tbody>';
$table .= '</table>';
$table .= '<table id=' . date("F-Y", strtotime($m[$currentKey]['created_timestamp'])) . ' class="tblclass">
<thead><tr><th>Month</th><th>ID</th><th>Customer</th></tr></thead>';
$table .= '<tbody>';
}
}
if($key == date("n", strtotime($value['created_timestamp']))-1) {
$table .= '<tr><td>'.date("F Y", strtotime($value['created_timestamp'])).'</td><td>' . $value['ID'] . '</td><td>' . $value['lastname'] . ' ' . $value['firstname'] . '</td></tr>';
}
if($lastKey == $count) {
$table .= '</tbody>';
$table .= '</table>';
}
$count++;
}
Sample Query 1 -
SELECT ID,NAME FROM USERS
Sample Query 2 -
SELECT Orders.OrderID as ID, Customers.CustomerName as Name, Orders.OrderDate as Date
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;
How can I load title headings to an array in PHP?
I mean
ID,NAME in Query 1 and ID,Name,Date in Query 2
This is what I'm trying to do :
I'm creating a PHP function to make HTML table automatically from any given MySQL-Select query
This where I'm up to now
function createTable($query) {
$sql_link = Connect_MySQLi_DB();// Database Connection
$sql_link->set_charset("utf8");
$result = $sql_link->query($query);
$headings = array('ID','Name','Date');//I need this array to create automatically
echo '<table>';
echo '<tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
echo '<th>'.$headings[$x].'</th>';
}
echo '<tr>';
while ($row = $result->fetch_object()) {
echo '<tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
echo '<td>' . $row->$headings[$x] . '</td>';
}
echo '<tr>';
}
echo '</table>';
}
So I need to create that $heading array automatically.
If I can do that, this function can display any MySQL-Select query as a HTML table
If you are using mysqli then fetch_fields seems to do the job.
EDIT:
Example:
$res = $db->query('SELECT A.id,A.a,A.id + B.id AS idd FROM A natural join B');
var_dump($res->fetch_fields());
Returns information about columns A.id, A.a and about the idd column (both tables have other columns). I omitted some fields from the output in order to make it shorter.
array(3) {
[0]=>
object(stdClass)#3 (13) {
["name"]=>
string(2) "id"
["orgname"]=>
string(2) "id"
["table"]=>
string(1) "A"
["orgtable"]=>
string(1) "A"
// more fields here
}
[1]=>
object(stdClass)#4 (13) {
["name"]=>
string(1) "a"
["orgname"]=>
string(1) "a"
["table"]=>
string(1) "A"
["orgtable"]=>
string(1) "A"
// more fields here
}
[2]=>
object(stdClass)#5 (13) {
["name"]=>
string(3) "idd"
["orgname"]=>
string(0) ""
["table"]=>
string(0) ""
["orgtable"]=>
string(0) ""
// more fields here
}
}
Finally this is how I made this function to work (Thanks Hynner for your excellent suggestion),
function createTable_from_sql_select_query($query) {
$sql_link = Connect_MySQLi_DB();// Database connection
$sql_link->set_charset("utf8");
$result = $sql_link->query($query);
// Adding Missing array_column Function for Old PHP Versions (<5.5)
if (!function_exists('array_column')) {
function array_column($array, $column) {
$ret = array();
foreach ($array as $row)
$ret[] = $row[$column];
return $ret;
}
}
$headings = json_decode(json_encode($result->fetch_fields()), true);
$headings = array_column($headings, 'name');
$return = '<table>';
$return .= '<thead><tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
$return .= '<th>' . ucwords(str_replace('_', ' ', (strtolower($headings[$x])))) . '</th>';
}
$return .= '</tr></thead><tbody>';
while ($row = $result->fetch_object()) {
$return .= '<tr>';
for ($x = 0; $x <= (count($headings) - 1); $x++) {
$return .= '<td>' . $row->$headings[$x] . '</td>';
}
$return .= '</tr>';
}
$return .= '</tbody></table>';
return $return;
}
Now anyone can convert any SQL select query to a HTML table.
I'm trying to check checkboxes based on previous user preferences that are stored in a CSV, but it is only running checking the first index in the CSV and skipping the rest. In the following code below if I pass it a CSV of "Sports, Lowkey, Wine" I want it to check those three on page load but it is only checking Sports
$typeArray = array(
"1" => "Sports",
"2" => "College",
"3" => "Pub",
"4" => "Night Club",
"5" => "Lowkey",
"6" => "Wine",
"7" => "Craft Beer",
);
$Sports="";
$College="";
$Pub="";
$NightClub="";
$Lowkey="";
$Wine="";
$CraftBeer="";
$string = "Sports, Lowkey, Wine";
$csv = str_getcsv($string, ", ");
for($i=0; $i<count($csv); $i++){
$index = array_search($csv[$i], $typeArray);
if($index == 1){
$Sports = "checked";
}
if($index == 2){
$College = "checked";
}
if($index == 3){
$Pub = "checked";
}
if($index == 4){
$NightClub = "checked";
}
if($index == 5){
$Lowkey = "checked";
}
if($index == 6){
$Wine = "checked";
}
if($index == 7){
$CraftBeer = "checked";
}
unset($index);
}
echo "<input type=\"checkbox\" name=\"Type[1]\" value=\"Sports\"" . $Sports . ">Sports ";
echo "<input type=\"checkbox\" name=\"Type[2]\" value=\"College\"" . $College . ">College ";
echo "<input type=\"checkbox\" name=\"Type[3]\" value=\"Pub\"" . $Pub . ">Pub ";
echo "<input type=\"checkbox\" name=\"Type[4]\" value=\"Night Club\"" . $NightClub . ">Night Club ";
echo "<input type=\"checkbox\" name=\"Type[5]\" value=\"Lowkey\"" . $Lowkey . ">Lowkey<br> ";
echo "<input type=\"checkbox\" name=\"Type[6]\" value=\"Wine\"" . $Wine . ">Wine ";
echo "<input type=\"checkbox\" name=\"Type[7]\" value=\"Craft Beer\"" . $CraftBeer . ">Craft Beer<br> ";
exchange this line
$index = array_search($csv[$i], $typeArray);
with this:
$index = array_search(trim($csv[$i]), $typeArray);
When you do a var_dump of $csv you will notice that there is a space before Lowkey and Wine:
array(3) {
[0]=> string(6) "Sports"
[1]=> string(7) " Lowkey"
[2]=> string(5) " Wine"
}
So your array_search will fail.
According to the manual, the delimiter in str_get_csv can be only one character. You can use explode or trim instead.
$csv = explode(', ', $string);
// or
$index = array_search(trim($csv[$i]), $typeArray);
I have a problem, were I need to loop through an array inside a "foreach-loop". The PHP code below is per now looping through the JSON and looking for ["Question"], and looping these correctly.
But these questions have different amounts of ["Answers"]. Also this JSON is made dynamically so I don't know from before how many questions/answers there'll be.
So what I need is the ["Answers"] should be looped withing the <li> inside each question.
Would be really greatful for some expertise here!
JSON
["Questions"]=>
array(2) {
[0]=>
object(stdClass)#13 (2) {
["Question"]=>
string(30) "My first questions is this...."
["Answers"]=>
array(2) {
[0]=>
object(stdClass)#14 (2) {
["Answers"]=>
string(18) "I like this answer"
["Correct"]=>
bool(true)
}
}
}
[1]=>
object(stdClass)#16 (2) {
["Question"]=>
string(22) "Another funny question"
["Answers"]=>
array(2) {
[0]=>
object(stdClass)#17 (2) {
["Answers"]=>
string(9) "Or is it?"
["Correct"]=>
bool(false)
}
[1]=>
object(stdClass)#18 (2) {
["Answers"]=>
string(10) "Yes it is!"
["Correct"]=>
bool(true)
}
}
}
}
PHP
$questions = array();
$i = 0;
foreach($question as $key => $items) {
$i++;
if ($i>1) {$hide=' hide';}
$questions[] = "
<div class='question-holder" . $hide . "' id='q" . $i . "'>
<h2>" . $items->Question . "</h2>
<ul class='answers' id='quiz-answers" . $i . "'>
<li>
<input tabindex='1' type='radio' name='txtAnswer" . $i . "' id='txtAlt1' value='sdsds'>
<label for='txtAlt1'><span>" . $items->Answers[0]->Answers . "</span></label>
</li>
</ul>
</div>";
}
Use a nested loop for the answers.
$tab = 0;
foreach ($question as $items) {
$i++;
$j = 0;
if ($i > 1) { $hide = ' hide'; }
$this_q = "<div class='question-holder" . $hide . "' id='q" . $i . "'>
<h2>" . $items->Question . "</h2>
<ul class='answers' id='quiz-answers" . $i . "'>
";
foreach ($items->Answers as $ans) {
$tab++;
$j++;
$qa = "$i-$j";
$this_q .= "<li>
<input tabindex='" . $tab . "' type='radio' name='txtAnswer" . $qa . "' id='txtAlt" . $qa . "' value='sdsds'>
<label for='txtAlt" . $qa . "'><span>" . $ans->Answers . "</span></label>
</li>
";
}
$this_q .= "</ul>
</div>";
$questions[] = $this_q;
}