Reputation: 15
So I have a page displaying an array of database information and each array ends with a ,
which means the very last array will also end with a ,
where well, it isn't supposed to.
The code looks like this:
if ($result-> num_rows > 0) {
echo "[";
while ($row = $result-> fetch_assoc()) {
echo "['".$row['row1']."'],['".$row['row2']."'],";
}
echo "];";
}
It then returns something like this:
[
['data1'],['data1'],
['data2'],['data2'],
];
Where I would like it to return this:
[
['data1'],['data1'],
['data2'],['data2']
];
So no matter how many rows there are the very last one will not have a ,
so the array can end, that is what I am trying to achieve.
Upvotes: 0
Views: 88
Reputation: 394
To answer the question, use rtrim
:
if ($result-> num_rows > 0) {
$output = "[";
while ($row = $result-> fetch_assoc()) {
$output .= "['".$row['row1']."'],['".$row['row2']."'],";
}
$output = rtrim($output, ",");
$output .= "];";
echo $output;
}
But let me suggest you to reevaluate what you are doing there because it doesn't look right. Depending on your end goal you may have better solutions.
Upvotes: 1