PHP table from explode array - php

I have data like this:
something something_description, something2 something2_description, something3 something3_description...
And now I need with PHP to get table as:
<tr><td>something</td><td>something_description</td></tr>
<tr><td>something2</td><td>something2_decription</td></tr>
I don't know how many "something" and "something_decriptions" will it be so I need to set some loop.
for now I have this code:
$data = explode(',',$query);
from that I will get array like:
[0] => something something_description
Now how can I put this into table?
On net I found some examples for sorting array to table, but this is with one more "explode" inside "explode"
I could use some help.

Probably you are looking for this:
$data = explode(',',$query);
echo '<table>';
foreach($data as $row){
echo '<tr>';
$row = explode(' ',$row);
foreach($row as $cell){
echo '<td>';
echo $cell;
echo '</td>';
}
echo '</tr>';
}
echo '</table>';

Try this:
echo "<table><tr>".implode("</tr><tr>",array_map(function($a) {return "<td>".implode("</td><td>",explode(" ",trim($a)))."</td>";},explode(",",$query)))."</tr></table>";
One-liner ftw :p

Related

Deleting Array ( [0] => from print_r output

I'm creating a script that will divide mysql results into three columns. Everything worked right but I'm getting my results in this way when I use print_r code:
Array ( [0] => Seat Siroku [title] => Seat Siroku )
Array ( [0] => Hyundai X35 [title] => Hyundai X35 )
And I should be getting them like this:
Seat Siroku
Hyundai X35
This is my PHP code:
$result = mysqli_query($link, "SELECT title FROM cars");
while($row = $result->fetch_array())
{
$rows[] = $row;
}
$lists = array_chunk($rows, ceil(count($rows) / 3));
foreach ($lists as $column) {
echo "<div class='column'>";
echo "<ul>";
foreach ($column as $title) {
echo '<li>';
print_r($title);
echo '</li>';
}
echo "</ul>";
echo "</div>";
}
I tried looking everywhere how can I remove this Array strings and I found an answer that print_r is causing it. When I try setting echo $title all I get is a Array to String conversation error. So how can I keep just the title as a result? Can someone help me with it? All the best!
You need to access the title column in each lowest level array:
$lists = array_chunk($rows, ceil(count($rows) / 3));
foreach ($lists as $column) {
echo "<div class='column'>";
echo "<ul>";
foreach ($column as $arr) {
echo '<li>';
echo $arr["title"];
echo '</li>';
}
echo "</ul>";
echo "</div>";
}
Remember that each $arr corresponds to one record from your result set. The confusion here might be coming from that you only selected a single column.

PHP Variable in a string in a string

I am attempting to echo a sting containing a variable already stored in a variable. Essentially I am building a class that can dynamically build tables based on a changing number of columns. I need get my db field names into the foreach loop before the foreach loop that has my db results, and then iterate over them in the loop. The problem is I have to store them in a loop prior to the db results loop; which is not recognizing it as a variable and just giving me a plain text '$row['myVar']'.
How can I get this to recognize the variable in the second loop?
$sqlVarNames = explode(', ', $sqlVar);
foreach ($sqlVarNames as $columnVar) {
$finalColumnVars .= '<td>\'. $row[\''.$columnVar.'\'] .\'</td>';
}
and then into my second loop
foreach ($sqlResult as $row) {
echo '<tr>';
echo $finalColumnVars;
echo '</tr>';
}
I tried all sorts of escape sequences on my $finalColumnVars and can't seem to get it to output the variable instead on plain text.
Here is what I get with the above code
<td>'. $row['client_name'] .'</td>
Is this possible?
$sqlVarNames = explode(', ', $sqlVar);
foreach ($sqlVarNames as $columnVar) {
$finalColumnVars .= '<td>'.$row[$columnVar].'</td>';
}
here is how you can merge these two loop and get the desired.
$sqlVarNames = explode(', ', $sqlVar);
foreach ($sqlResult as $row) {
echo '<tr>';
foreach ($sqlVarNames as $columnVar) {
echo '<td>'. $row[$columnVar] .'</td>';
}
echo '</tr>';
}

How to change "while" loop to a "foreach" loop

I would like to ask a question about "foreach loop" in PHP. Towards the bottom of the code below, the "while" loop accesses elements from an array individually. How can I rewrite the BODY of the while loop using a "foreach" loop?
<?php
require_once('MDB2.php');
$db = MDB2::connect("mysql://mk:mk#shark.company.com/mk");
if(PEAR::iserror($db)) die($db->getMessage());
$sql = "SELECT courses.ID,courses.Name,staff.Name
FROM courses,staff
WHERE courses.Coordinator=staff.id
and courses.ID = \"$course\"";
$q = $db->query($sql);
if(PEAR::iserror($q)) die($q->getMessage());
while($row = $q->fetchRow()){
echo "<tr><td>$row[0]</td>\n";
echo "<td>$row[1]</td>\n";
echo "<td>$row[2]</td></tr>\n";
}
}
?>
</table>
</body></html>
Perhaps:
echo "<tr>";
foreach( $row as $field => $value )
{
echo "<td> \"$value\" </td>";
}
echo "</tr>";
As Poitr Olaszewski commented. You will need to fetch the whole collection to be able to itterate through using foreach().
That means instead of the whole while($row...., you'd do something like this:
$data = $q->fetchAll();
foreach($data as $key => $val) {
// do what you need to here....
}
More reading -> Documentation for fetchAll() for MDB2.php

MySQL Row in one output

Im pretty new to MySQl and PHP. I need some help with a small issue.
My statement is as follows:
while($row = $stmt->fetch()) {
$return_arr[] = $row['name'];
$return_arr[] = $row['value'];
}
It outputs as follows:
Mr James Jones
23
How can I bring it together into one line? Like this:
Mr James Jones 23
Thank you
Use implode to join the array elements:
echo implode(' ', $return_arr);
Do like this
while($row = $stmt->fetch()) {
$return_arr[] = $row['name']." ".$row['value'];
}
//print_r($return_arr); // The results gets printed as you expected or you could make use of a foreach construct as shown below.
//Printing using a foreach construct
foreach($return_arr as $k=>$v)
{
echo $v;echo "<br>";
}
Just use like this,
while($row = $stmt->fetch()) {
$return_arr[] = $row['name']. ' '.$row['value'];
}
it will work.
And if you want any other help let me know.
An alternate way is handling it inside your mysql query:
SELECT CONCAT(name, ' ', value) as name_and_value FROM ....
Than you can use
$row['name_and_value']
in your php code.

How to sum result of query

I have one query where the output processing looks like this:
while($row = mysql_fetch_array($result)){
echo $row['username'] . " " . $row['earning'];
}
And outputs result is like this:
JOHN 200
JOHN 350
NEO 100
NEO 220
What I want to achieve is that every name appears once, and "earning" is sum of all earnings of that name, like this:
JOHN 550
NEO 320
I have to mention that I CANNOT change the query; that is biggest problem.
Is there any hope? Some suggestions? :)
You can sum the values in the loop to another array and then output it.
Try:
$earnings = array();
while($row = mysql_fetch_array($result)) {
if (!isset($earnings[$row['username']])) $earnings[$row['username']] = 0;
$earnings[$row['username']] += $row['earning'];
}
foreach($earnings as $user => $earnings) {
echo "$user $earnings<br />\n";
}
try:
$user = array();
while($row = mysql_fetch_array($result)){
$user[$row['username']] += $row['earning'];
}
to do echo :
foreach($user as $key => $value) {
echo $key."=". $earnings."<br>";
}
To get a quick solution to this answer you may want to simply append these results to an associated array and then simply loop over it to get the final count.
So, something like this:
$names= array();
while($row = mysql_fetch_array($result)){
$names[$row["username"]] += $row["earning"];
}
foreach($names as $k => $v) {
echo $k." ".$v."\n";
}
Instead of just selecting the data, select the field and SUM(otherfield) with otherfield being the field with the number to be summed. Then add GROUP BY with the first field.
try this in mysql side you don't need to calculate in php side so don't change your PHP side code jst change query like this
SELECT
username,
SUM(earning)
FROM yourtable
GROUP BY (username)
hope its will work for you

Categories