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
Related
I am trying to remove the last comma(,) from foreach loop in php with the following code
<?php
foreach ($snippet_tags as $tag_data) {
$tags_id = $tag_data->tag_id;
$tagsdata = $this->Constant_model->getDataOneColumn('tags', 'id', $tags_id);
$tag_name=$tagsdata[0]->tag_name;
?>
<?php echo $tag_name; ?> ,
<?php }
?>
Right I am getting result like
Hello, How, sam,
But i wants to remove the last comma
By placing the HTML in a simple string variable and then using rtrim() on the resulting string before outputting it this should remove the final , from the string
<?php
$out = '';
foreach ($snippet_tags as $tag_data) {
$tags_id = $tag_data->tag_id;
$tagsdata = $this->Constant_model->getDataOneColumn('tags', 'id', $tags_id);
$tag_name=$tagsdata[0]->tag_name;
// move inside loop and amend to place in a simple string var
$out .= '' . $tag_name . ',';
?>
echo rtrim($out, ',');
You can also use the following code -
<?php
$numItems = count($snippet_tags);
$i = 0;
foreach ($snippet_tags as $tag_data) {
$tags_id = $tag_data->tag_id;
$tagsdata = $this->Constant_model->getDataOneColumn('tags', 'id', $tags_id);
$tag_name=$tagsdata[0]->tag_name;
?>
if(++$i === $numItems)
echo "<a href='base_url() ?>tags/<?php echo $tag_name;'> $tag_name</a>";
else echo "<a href='base_url() ?>tags/<?php echo $tag_name;'> $tag_name</a> ,";
<?php
}
?>
I am newer to PHP and I am able to get the desired output but I am doing it one index position at a time. I am returning data from a .txt file and I need to insert this data into an HTML table I am creating using PHP. BUT FIRST I need to be able to get the same output without typing out every index position. I tried to use a forloop but it kept outputting only one line.
I manually outputted the lines from the file and it works. What loop in PHP would be best to achieve the same results and output these elements? IMPORTANT, as is I am able to sort and rsort (I want to be able to do this so if it can be implemented in the loop that would be awesome) any help is more than I have right now.
PHP
$books = array();
if ($fp)
{
while(true)
{
$lines_in_file = count(file($filename));
$line = fgets($fp);
if (feof($fp))
{
break;
}
$line_ctr++;
list($title, $author, $pubdate, $isbn) = explode('*', $line);
$new_line = explode('*', $line);
for($ii= 1; $ii <= $lines_in_file; $ii++){
$lines = fgets($fp); //Read each line
$member = trim($lines);
array_push($books, $member);
}
//This foreach only brings back the first like in the txt file, why?
$cntr = 0;
foreach($books as $element){
$cntr++;
$table .= "<tr>";
$table .= "<td>".$title."</td>";
$table .= "<td>".$author."</td>";
$table .= "<td>".$pubdate."</td>";
$table .= "<td>".$pubdate."</td>";
$table .= "<td>".$isbn."</td>";
$table .= "</tr>\n"; //added newline
echo $element;
}
//sort($books);
// rsort($books);
echo $books[0];
echo "<br>";
echo $books[1];
echo "<br>";
echo $books[2];
echo "<br>";
echo $books[3];
echo "<br>";
echo $books[4];
echo "<br>";
echo $books[5];
echo "<br>";
echo $books[6];
echo "<br>";
echo $books[7];
echo "<br>";
echo $books[8];
echo "<br>";
echo $books[9];
echo "<br>";
echo $books[10];
echo "<br>";
echo $books[11];
echo "<br>";
echo $books[12];
echo "<br>";
echo $books[13];
echo "<br>";
echo $books[14];
echo "<br>";
echo $books[15];
echo "<br>";
echo $books[16];
echo "<br>";
echo $books[17];
}//END WHILE LOOP
fclose($fp ); //Close file
}
Having to make a few guesses here but i believe the file is going to look like:
title*author*pubdate*isbn
title*author*pubdate*isbn
title*author*pubdate*isb
if this is wrong, let me know
as long as the fie is not to large read it in to an array:
$book_array=file('book_file.txt');
//print_r($book_array); //is it an array of the books, one book per array key
now to separate each line:
foreach($book_array as $line){
$line_sep=explode('*',$line);
// with no sorting option you could just echo inside the loop
//if you want to keep sorting options we have to keep the separated lines
$new_book_array[]=$line_sep;
}
unset($book_array);//free up memory if needed
//print_r($new_book_array);//is it a multi-d array, book then the 4 elements
to sort our new multidimensoanl array:
usort($new_book_array, function($a, $b) {
return strcmp($a['0'], $b['0']);;
}); //this sorts on key 0 in your case title:
//print_r($new_book_array); // has it sorted properly
for display:
loop again
echo '<table><tr><th>Title</th><th>Author</th><th>Pub Date</th><th>ISBN</th></tr>';
foreach($new_book_array as $book){
//print_r($book); //is it each indervidual book array with 4 elements
echo '<tr><td>'.$book[0].'</td><td>'.$book[1].'</td><td>'.$book[2].'</td><td>'.$book[3].'</td></tr>';
}
echo '</table>';
I have an array coming from a .csv file. These are coming from a real estate program. In the second column I have the words For Sale and in the third column the words For Rent that are indicated only on the rows that are concerned. Otherwise the cell is empty. I want to display a list rows only For Sale for example. Of course then if the user clicks on a link in one of the rows, the appropriate page will be displayed.
I can't seem to target the text in the column, and I can't permit that the words For Sale be used throughout the entire array because they could appear in another column (description for example).
I have tried this, but to no avail.
/* The array is $arrCSV */
foreach($arrCSV as $book) {
if($book[1] === For Sale) {
echo '<div>';
}
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
I also tried this:
foreach($arrCSV as $key => $book) {
if($book['1'] == 'For Sale') {
echo '<div>';
}
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
Do you mean:
foreach($arrCSV as $key => $book) {
if($book['1'] == 'For Sale') {
echo '<div></div>';
}else{
echo '<div>';
echo $book[0]. '<br>';
echo $book[1]. '<br>';
echo $book[2]. '<br>';
echo $book[3]. '<br>';
echo $book[6]. '<br><br><br>';
echo '</div>';
}
}
I found a solution here:
PHP: Taking Array (CSV) And Intelligently Returning Information
$searchCity = 'For Sale'; //or whatever you are looking for
$file = file_get_contents('annonces.csv');
$results = array();
$lines = explode("\n",$file);
//use any line delim as the 1st param,
//im deciding on \n but idk how your file is encoded
foreach($lines as $line){
//split the line
$col = explode(";",$line);
//and you know city is the 3rd element
if(trim($col[1]) == $searchCity){
$results[] = $col;
}
}
And then:
foreach($results as $Rockband)
{
echo "<tr>";
foreach($Rockband as $item)
{
echo "<td>$item</td>";
}
echo "</tr>";
}
As you can see I'm learning. It turns out that by formulating a question, a series of similar posts are displayed, which is much quicker and easier than using google. Thanks.
I want to put my outputted PHP into a table but it doesn't like it...
The layout I want is like this
ROW - Desctiption URL
ROW2- Meta Description
And it needs to keep this same layout even when I enter more then one URL.
What happens now is that when I input lots of urls it puts all of the same parts into the same cell.. How can I change this?
Sorry its hard to explain...
Here is the code:
<?php
ini_set( "display_errors", 0);
//make the array
$TAarray = explode("\n", strip_tags($_POST['TAData']));
foreach ($TAarray as $key => &$line) {
$line = trim($line);
// get the meta data for each url
$tags = get_meta_tags($line);
echo '<tr>';
echo (isset($tags['description']))?"<tr><td>Description($line)</td> </tr>".$tags['description']:"<tr><td>Description($line)</td></tr><tr><td>No Meta Description</td></tr>.";
echo '</tr>';
}
?>
You've got some awkward HTML there.. Try doing it like this:
//start the table
echo "<table>";
foreach ($TAarray as $key => &$line) {
$line = trim($line);
// get the meta data for each url
$tags = get_meta_tags($line);
//start a new row in the table
echo '<tr>';
if(isset($tags['description'])){
//add two cells to the table.
echo "<td>Description($line)</td>";
echo "<td>{$tags['description']}</td>";
} else {
echo "<td>Description($line)</td>"
echo "<td>No Meta Description</td>";
}
echo '</tr>';
}
echo "</table>";
//make the array
$data='http://stackoverflow.com
http://ebay.com/';
$TAarray = explode("\n", strip_tags($data));
echo "<table>";
foreach ($TAarray as $key => &$line) {
$line = trim($line);
// get the meta data for each url
$tags = get_meta_tags($line);
echo '<tr>';
if(isset($tags['description'])){
echo "<tr><td>Description($line):".$tags['description']:" </td> "; else{
"</tr><tr><td>Description($line)</td></tr><tr><td>No Meta Description</td></tr>.";
echo '</tr>';
}
}
echo "</table>";
I'm parsing out an HTML table and building an array based on the row values. My problem is the associative keys that are returned have a bit of white space at the end of them giving me results like this:
Array ( [Count ] => 6 [Class ] => 30c [Description] => Conformation Model (Combined 30,57) )
So a line like this:
echo $myArray['Count'];
or
echo $myArray['Count '];
Gives me a blank result.
for now I've got a pretty hacky work around going...
foreach($myArray as $row){
$count = 0;
foreach($row as $info){
if($count == 0){
echo 'Count:' . $info;
echo '<br>';
}
if($count == 1){
echo ' Class:' . $info;
echo '<br>';
}
if($count == 2){
echo ' Description:' . $info;
echo '<br>';
}
$count++;
}
}
The function I'm using to parse the table I found here:
function parseTable($html)
{
// Find the table
preg_match("/<table.*?>.*?<\/[\s]*table>/s", $html, $table_html);
// Get title for each row
preg_match_all("/<th.*?>(.*?)<\/[\s]*th>/", $table_html[0], $matches);
$row_headers = $matches[1];
// Iterate each row
preg_match_all("/<tr.*?>(.*?)<\/[\s]*tr>/s", $table_html[0], $matches);
$table = array();
foreach($matches[1] as $row_html)
{
preg_match_all("/<td.*?>(.*?)<\/[\s]*td>/", $row_html, $td_matches);
$row = array();
for($i=0; $i<count($td_matches[1]); $i++)
{
$td = strip_tags(html_entity_decode($td_matches[1][$i]));
$row[$row_headers[$i]] = $td;
}
if(count($row) > 0)
$table[] = $row;
}
return $table;
}
I'm assuming I can eliminate the white space by updating with the correct regex expression, but, of course I avoid regex like the plague. Any ideas? Thanks in advance.
-J
You can use trim to remove leading and trailing whitespace characters:
$row[trim($row_headers[$i])] = $td;
But don’t use regular expressions for parsing the HTML document; use a proper HTML parser like the Simple HTML DOM Parser or the one of DOMDocument instead.
An easy solution would be to change
$row[$row_headers[$i]] = $td;
to:
$row[trim($row_headers[$i])] = $td;