I would like to start out saying I don't want to use Javascript....
I have an array which is returning correctly I believe, however I am only having the first entry in the array display in the drop down list.
Is this a problem with the array? or with this function?
foreach($array as $key=>$value){
$html = "<option value='$key'>$value</key>";
}
echo "<select name="process">$html</select>";
You have to use the concatenation operator (.):
$html = '';
foreach($array as $key => $value)
{
$html.= "<option value='$key'>$value</option>";
}
echo "<select name=\"process\">$html</select>";
However, looking at the function you posted earlier, mysql_fetch_assoc only returns a single row at a time. You need to loop over that, instead. The following should suffice:
function tasks_list($p_id) {
$project_tasks = array();
$p_id = (int)
$p_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
$result = mysql_query("SELECT task_name FROM tasks WHERE project_id = $p_id");
while($project_tasks = mysql_fetch_assoc($result))
{
$html.= "<option value='".$project_tasks['task_name']."'>".$project_tasks['task_name']."</option>";
}
echo "<select name=\"process\">$html</select>";
}
You need to concat the strings. Start by initializing $html to an empty string before starting your for loop.
$html = '';
foreach($array as $key => $value)
{
$html .= "<option value='$key'>$value</key>";
// same as $html = $html . "<option value='$key'>$value</key>";
}
Note: There is also a typo in your code:
echo "<select name="process">$html</select>";
should either be:
echo "<select name=\"process\">$html</select>";
OR
echo "<select name='process'>$html</select>";
if that's what you meant.
$html = "";
foreach ($array as $key => $value){
$html .= "<option value='$key'>$value</option>";
}
echo "<select name='process'>$html</select>";
= reassigns; .= appends
If you use = it reassigns $html in every iteration, so that $html will contain the result of the last iteration - one single option.
Related
So I am creating a dynamic menu. Where I have stored the main categories of the menu in a separate table and subcategories in another table.
They are stored in this way
Categories Table
id cat_name
1 HOME,
2 PRODUCTS,
3 SOLUTIONS,
4 NEWS & GALLERY,
5 DOWNLOADS,
6 CONTACT
Right Now I am running a query
$sql="SELECT * FROM categories";
$query = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($query)) {
$row['cat_name'];
$cat=explode(",",$row['cat_name']);
}
Then wherever needed I am printing the values like this
<?php echo $cat[0]; .. echo $cat[1]; //and so on ?>
It looks like this right now. And it is supposed to look likethis
But the problem with this solution is that I have to define the index of the array to print it.
I am developing the admin panel for this one and I want that if the admin adds a new menu item then it should automatically fetch it and display it.
But with this solution it is not possible.
I am thinking of iterating the values with a for loop but cannot get it right.
Use foreach ($query as $rows)
or
Use for ($i=0; $i < count($query); $i++)
Probably You can try this also
$sql="SELECT * FROM categories";
$query = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($query))
{
$row['cat_name'];
$cat=explode(",",$row['cat_name']);
foreach($cat as $catss)
{
$cat = trim($catss);
$categories .= "<category>" . $cat . "</category>\n";
}
}
You can try this way may be you wish like this for dynamic menu:
$sql="SELECT * FROM categories";
$query = mysqli_query($con, $sql);
$menu = '';
$menu .= '<ul>';
while($row = mysqli_fetch_assoc($query))
{
$menu .= '<li>' . $row['cat_name'] . '</li>';
}
$menu .= '</ul>';
echo $menu;
When you are fetching data from table then you can directly print that value using field name. if you want to further use that so, you have to add in one array like:
$cat[] = $row['cat_name'];
then you can use this value in that manner using for or while:
foreach ($cat as $value) {
echo $value;
}
echo '<ul>';
foreach ($cat as $val) {
echo "<li>{$val}</li>";
}
echo '</ul>';
Instead of the index. Also this should be faster and readable than for loop.
You can save it in array then later access the values.
$sql="SELECT * FROM categories";
$query = mysqli_query($con, $sql);
$cat = array();
while($row = mysqli_fetch_assoc($query)) {
$cat[]=$row['cat_name']
}
Now:
foreach ($cat as $category) {
$cate_gory = explode("," , $category);
foreach ($cate_gory as $categories) {
echo $categories . "<br>";
}
}
Foreach Loop
foreach($cats as $cat)
{
echo $cat;
}
Basic For Loop
for ($i=0; $i<count($cats); $i++)
{
echo $cats[$i];
}
Simple Use Case
<?php
$cats = 'Stack overflow PHP questions';
$cats = explode(' ',$cats);
$html = '<ul>';
foreach($cats as $cat)
{
$html .= '<li>' . $cat . '</li>';
}
$html .= '</ul>';
echo $html;
?>
Your Code
In this case the while loop you are using will iterate over all the values returned from the sql statement, so there is no need to add more complexity. I would remove the commas from the field names and echo out the html this way.
$sql="SELECT * FROM categories";
$query = mysqli_query($con, $sql);
$html = '<ul>';
while($row = mysqli_fetch_assoc($query)) {
$html .= '<li>' . $row['cat_name'] . '</li>';
}
$html .= '</ul>';
echo $html;
?>
I am trying to create an array from this data, but I donĀ“t get it. I tried with the array_merge function, but the array doesn't construct correctly. This is my code, I want to create an array with the different fields of the table.
<?php
require('extractorhtml/simple_html_dom.php');
$dom = new DOMDocument();
//load the html
$html = $dom->loadHTMLFile("http:");
//discard white space
$dom->preserveWhiteSpace = false;
//the table by its tag name
$tables = $dom->getElementsByTagName('table');
//get all rows from the table
$rows = $tables->item(0)->getElementsByTagName('tr');
echo '<input type="text" id="search" placeholder="find" />';
echo '<table id="example" class="table table-bordered table-striped display">';
echo '<thead>';
echo '<tr>';
echo '<th>Date</th>';
echo '<th>Hour</th>';
echo '<th>Competition</th>';
echo '<th>Event</th>';
echo '<th>Chanel</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
// loop over the table rows
foreach ($rows as $row)
{
// get each column by tag name
$cols = $row->getElementsByTagName('td');
// echo the values
echo '<tr>';
echo '<td>'.$cols->item(0)->nodeValue.'</td>';
echo '<td>'.$cols->item(1)->nodeValue.'</td>';
echo '<td>'.$cols->item(3)->nodeValue.'</td>';
echo '<td class="text-primary">'.$cols->item(4)->nodeValue.'</td>';
echo '<td>'.$cols->item(5)->nodeValue.'</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
?>
You don't need to merge arrays, you just need to push onto a new array to create a 2-dimensional array.
$new_array = array();
foreach ($rows as $row)
{
// get each column by tag name
$cols = $row->getElementsByTagName('td');
// echo the values
echo '<tr>';
echo '<td>'.$cols->item(0)->nodeValue.'</td>';
echo '<td>'.$cols->item(1)->nodeValue.'</td>';
echo '<td>'.$cols->item(3)->nodeValue.'</td>';
echo '<td class="text-primary">'.$cols->item(4)->nodeValue.'</td>';
echo '<td>'.$cols->item(5)->nodeValue.'</td>';
echo '</tr>';
$new_array[] = array(
'date' => $cols->item(0)->nodeValue,
'hour' => $cols->item(1)->nodeValue,
'competition' => $cols->item(3)->nodeValue,
'channel' => $cols->item(5)->nodeValue
);
}
Based on your <th> values, you know which columns contain which values, so it looks like you'd just need to modify the code inside your foreach loop to append the values to an array rather than generating new HTML with them.
foreach ($rows as $row)
{
// get each column by tag name
$cols = $row->getElementsByTagName('td');
$array['date'] = $cols->item(0)->nodeValue;
$array['hour'] = $cols->item(1)->nodeValue;
$array['competition'] = $cols->item(3)->nodeValue;
$array['event'] = $cols->item(4)->nodeValue;
$array['chanel'] = $cols->item(5)->nodeValue;
$result[] = $array;
}
After this loop, $result will be an array of arrays containing the values from the <td>s, where each inner array represents one <tr>.
I have this code:
$sql = 'SELECT * from page';
$result = $pdo->query($sql);
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
if(count($result)) {
echo '<table><tr>';
foreach ($rows[0] as $columnName => $value) {
echo '<th>' . $columnName . '</th>';
}
echo '</tr>';
foreach ($rows as $row) {
echo '<tr>';
foreach ($row as $value) {
echo '<td>' . $value . '</td>';
}
echo '<tr>';
}
echo '</table>';
}
This code is working fine. But since my table is huge, it is appearing to be very very clumsy - almost unreadable. And I don't know how to make it appear better. I tried adding spaces and tabs but to no use. I can't understand how to do it. I got this code from my friend. Can anyone modify the code so as to add at least a tab space between every column. Help would be really appreciated.
You can for example do the following:
instead of
echo '<table><tr>';
use
echo '<table border="1"><tr>';
It will put border on your table and it will be easier to differentiate between cells
I have a table with data from sql. Some of the columns in the db have more than 1 name. I have created an array from them but now I need to compare the two while creating a table.
$strArrayChildren = explode(',', $children);
$strArrayChildren = str_replace('and', '', $strArrayChildren);
$childCount = count($strArrayChildren);
$strArrayGrades = explode(',',$the_grades);
$strArrayGrades = str_replace('(', '', $strArrayGrades);
$strArrayGrades = str_replace(')', '', $strArrayGrades);
$grades ='';
foreach($strArrayChildren as $child){
foreach($strArrayGrades as $grade){
if(strpos($grade, $child) !== false){
$grades = preg_replace('([a-z A-Z ()]+)', "", $grade);
}elseif(strpos($grade, $child) !== true){
$grades ='';
}
}
echo "<tr>";
echo "<td>{$child}</td>";
echo "<td>{$last_name}</td>";
echo "<td>Child</td>";
echo "<td>{$grades}</td>";
echo "</tr>";
}
When I run this code I get the grade of the student to match with the first name from the array, but then the rest of the grades keep trying to match with the first student even though there is a new row with a new name.
Any help would be great! Thank you!
I'm not sure about your database but this should work. I'm posting the response with static arrays.
<?php
$strArrayChildren = array("Becky"," Aaron"," Luke");
$the_grades = "9 (Susan), 5 (Luke)";
$strArrayGrades = explode(',',$the_grades);
echo "<html><body><table style='text-align: center; width: 400px;'>";
echo "<tr>";
echo "<td>Child</td>";
echo "<td>Grade</td>";
echo "</tr>";
foreach($strArrayChildren as $child){
$grades = "";
$child = trim($child);
foreach($strArrayGrades as $key => $grade){
if(strpos($grade, $child) > 0){
$grades = intval(preg_replace('/[^0-9]+/', '', $grade), 10);
}
}
echo "<tr>";
echo "<td>{$child}</td>";
echo "<td>{$grades}</td>";
echo "</tr>";
}
echo "</table></body></html>";
?>
Explanation:
you need to initialize $grades right after first loop start
There is no point to test both states of strpos() function
It's safe to check position of needle occurrence in the string (be grater than 0)
You need to change you regex for selecting numbers from an string.
Trim needle in strpos(); there are unwanted white space in some cases. Better to trim white spaces at the start of the loop
I'm a newbie at GA API so I have no clue how to extract results the correct way in this case.
e.g. I'm trying to extract avgTimeOnPage values based on filtering from ga:pagePath = ...
But each one is returning a single digit value on ga:pagePath.. so I'm thinking the ga:pagePath and ga:avgTimeOnPage results are not being displayed correctly. Maybe I'm not extracting the right way.
Anyone who can help would be greatly appreciated.
$ids = 'ga:123456789';
// $start_date $end_date already defined
$filter = 'ga:pagePath==/folder/somepage.html';
$metrics = 'ga:avgTimeOnPage';
$optParams = array('dimensions' => 'ga:pagePath', 'filters' => $filter);
$data = $service->data_ga->
get($ids, $start_date, $end_date, $metrics, $optParams);
foreach($data['totalsForAllResults'] as $rows) :
echo $rows['ga:pagePath']; // why returning a single digit value?
echo $rows['ga:avgTimeOnPage']; // also returns a single digit
endforeach;
$data['totalsForAllResults'] will return a single row that is the total row. You are looking for the values not the totals. so you should use:
foreach ($data->getRows() as $row) :
And then you can iterate $rows for every cell.
Check this full example:
private printDataTable(&$results) {
if (count($results->getRows()) > 0) {
$table .= '<table>';
// Print headers.
$table .= '<tr>';
foreach ($results->getColumnHeaders() as $header) {
$table .= '<th>' . $header->name . '</th>';
}
$table .= '</tr>';
// Print table rows.
foreach ($results->getRows() as $row) {
$table .= '<tr>';
foreach ($row as $cell) {
$table .= '<td>'
. htmlspecialchars($cell, ENT_NOQUOTES)
. '</td>';
}
$table .= '</tr>';
}
$table .= '</table>';
} else {
$table .= '<p>No Results Found.</p>';
}
print $table;
}
source: https://developers.google.com/analytics/devguides/reporting/core/v3/coreDevguide#working