Remove foreach last comma PHP [duplicate] - php

This question already has answers here:
Removing last comma from a foreach loop
(9 answers)
Closed 6 years ago.
How to remove last comma from the output of a foreach() loop?
Can someone please help modify this code for me.
$sth = $dbh->query('SELECT * FROM `stage5` ORDER BY `stage5`.`lenght` DESC');
$sth->setFetchMode(PDO::FETCH_ASSOC);
$result = $sth->fetchAll();
foreach($result as $r) {
echo $r['lenght'], ",";
}
This prints
105.4,102.1,
Below would be correct
105.4,102.1
I have read many posts related to this but, I can't get it working and I don't get it. Any help is appreciated!

One way to solve this is to not echo out the commas in the foreach loop. Put the data you want to echo into an array, then use implode.
$output = array();
foreach($result as $r) {
$output[] = $r['lenght'];
}
echo implode(',', $output);

I would just take a functional approach:
<?php
$result = $sth->fetchAll();
echo implode(',', array_column($result, 'length'));
Note that array_column() requires PHP 5.5+.

Related

PHP Return Array in JSON , what happen this return include index? How To Fix? [duplicate]

This question already has answers here:
mysqli_fetch_array Gives Me Duplicate Rows
(4 answers)
Closed 3 years ago.
enter image description here
$table = $this->Execute("select * from data ");
$result = array();
while($row = mysqli_fetch_array($table))
{
array_push($result, $row);
}
return $result;
this my code,
i dont know why my result including the index
Its because of this statement:
while($row = mysqli_fetch_array($table))
You are getting numeric indexes as well as text keys.
Replace this by:
while($row = mysqli_fetch_assoc($table)) // will return only associate (string) keys.
OR
while($row = mysqli_fetch_array($table, MYSQLI_ASSOC)) // will return only associate (string) keys.
This will not include numeric indexes.
References:
mysqli_fetch_assoc()
mysqli_fetch_array()

loop 2 times through a pdo result [duplicate]

This question already has answers here:
Resetting array pointer in PDO results
(7 answers)
Closed 9 years ago.
I am fetching the results from a db with PDO::FETCH_ASSOC. The issue is that I am doing it twice in the same file. Is that a known issue? What would be the alternative?
Here is my code:
FIRST TIME
while($row = $ordersQuery->fetch(PDO::FETCH_ASSOC))
{
$totalAmount += $row['clientPrice']/100;
}
echo $totalAmount;
SECOND TIME
while($row = $ordersQuery->fetch(PDO::FETCH_ASSOC))
{
....
}
Whenever I remove the first fetching, the second works fine. If I have both, the second does not return anything.
Thanks!
You can't fetch from the DB multiple times like this. Do this instead:
$orders = $ordersQuery->fetchAll(PDO::FETCH_ASSOC);
...
foreach ($orders as $val) {
// stuff 1
}
...
foreach ($orders as $val) {
// stuff 2
}
Use fetchAll() which will return an array. You then can loop through it as many times as you want:
$orders = $ordersQuery->fetchAll(PDO::FETCH_ASSOC);

PHP: why can't I loop twice on mysqli_fetch_array() results? [duplicate]

This question already has answers here:
Mysqli query doesn't work twice
(2 answers)
Closed 5 years ago.
I'm retrieving some data from a mysql database. There are two loops which uses the same result set.
while ($row = mysqli_fetch_array($newsQuery)) {
echo "<a href='news-article.php?articleId=" .$row["news_id"]."' class='list-group-item active'>".$row["news_title"]."</a>";
}
This loop ends with success. then in the same page I have the following loop.
while ($row = mysqli_fetch_array($newsQuery)) {
echo $row["news_content"];
}
This loop doesn't return anything even if there are content in the table. When I try it in the first loop. the content is displayed correctly. Any idea on what I'm doing wrong.
From PHP's mysqli_fetch_array DOCS:
Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.
You are using a 'while' loop on $row = mysqli_fetch_array($newsQuery)
This means the loop will keep going untill mysqli_fetch_array($newsQuery) returns NULL.
This is the reason why you cant use that loop again, since mysqli has finished fetching the results and the mysqli_fetch_array($newsQuery) now returns NULL untill you make a new query.
Try populating a variable with the results first, then loop on that variable:
$results = array();
while ($row = mysqli_fetch_array($newsQuery)) {
$results[] = $row;
}
foreach ($results as $key => $row) {
echo "<a href='news-article.php?articleId=" .$row["news_id"]."' class='list-group-item active'>".$row["news_title"]."</a>";
}
foreach ($results as $key => $row) {
echo $row["news_content"];
}
While it is best to avoid logic that results in looping through a result set twice, if necessary you need to reset the result set back to the start:-
mysqli_data_seek($newsQuery, 0);
Because you already fetch the value of $newsQuery Try this code
//temporary save the news content into array
$content = array();
$x=0;
while ($row = mysqli_fetch_array($newsQuery)) {
echo "<a href='news-article.php?articleId=" .$row["news_id"]."' class='list-group-item active'>".$row["news_title"]."</a>";
$content[$x]= $row["news_content"];
$x++;
}
and if you want to retrieve it
//now retrieve it
for($y=0; $y<count($content); $y++)
{
echo $content[$y]+"<br/>";
}

Create an array from values from mysql table [duplicate]

This question already has answers here:
Creating an array from a MySQL table
(2 answers)
Closed 10 years ago.
I am using PHPlot to make a graph.
I have an issue in generating the array from a MySQL table.
Basivally, I want to array is as follows:
$values = array($arrayx);
array('a',-3),
array('b',5),
array('c',7),
array('d',8),
array('e',12),
array('f',-6),
//);
$graph->SetDataValues($values);
$graph->SetXTickPos('none');
$graph->SetXTickLabelPos('none');
Part of the code where I tried to retrieve values from table to feed the array
$query="SELECT * FROM tasks";
$result=mysql_query($query);
//using a for loop to add values to the array
while ($resource=mysql_fetch_array($result)){
$thedate = $resource["date"];
$title = $resource2["title"];
$innerarray = "array('.$thedate.', $title),";
}
$values = array($innerarray).");";
$graph->SetDataValues($values);
$graph->SetXTickPos('none');
$graph->SetXTickLabelPos('none');
//Draw it
$graph->DrawGraph();
}
The way I'm doing the $innerarray and $values seems wrong. Can you please help me fix it?
Thank you
try replacing
$innerarray = "array('.$thedate.', $title),";
with
$innerarray = array($thedate, $title);
$new = array();
while(for condition ){
$new[] = '\''.thedate[$i].''\','.$title[$i].'\';
}
var_dump($new);
this an idea, you need to edit the code to make it working
I assume it is this that you want:
$sql="SELECT datefield, titlefield FROM tasks";
....
while (list($thedate,$thetitle) = mysql_fetch_array($result)) {
$values[] = array($thedate,$thetitle);
}
echo $values[0][0]; // will output your 1st date
echo $values[0][1]; // will output your 1st title

Can I convert individual fields of a 'mysql_query' to arrays? [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
Likely a remedial question, but in all my days as a PHP user I have yet to encounter an answer. Basically, is there any way to grab a single field of a "mysql_query" as an array? For instance say I have the following:
$query = "Select id,first_name,last_name FROM people";
$result = mysql_query($query);
Is there any way to grab each (id, first_name, last_name) as individual arrays without iterating through the recordset? Can I say something like:
$ids = field_to_array($result['id']);
$first_names = field_to_array($result['first_name']);
$last_names = field_to_array($result['last_name']);
As I said, in the past I've always simply built the arrays as needed, but an existing method would be handy.
mysql doesn't have that as a native function. you could always write your own..
function mysql_convert_cols($dataset) {
foreach ($dataset as $row => $values) {
foreach ($values as $column => $value) {
$return[$$column][$row] = $value;
}
}
return($return);
}
$resultConverted = mysql_convert_cols($result);
$id=$resultConverted['id'];
$firstName=$resultConverted['firstName'];
I'm not sure why do you need this , but you can do it like this :
$resultArray = array();
while($row = mysql_fetch_array($result)){
$resultArray[] = array(
"id" => $row['id'],
"firstName"=>$row['first_name'],
"lastName"=>$row['last_name']
);
}
Check if values are in :
print_r($resultArray);
Then you can foreach or to do the for loop on values.

Categories