I need to get an array output as this [[1, 26], [3, 16], [3, 17], [4, 27], [4, 26]]
from the following php mysql code
include("db.php");
$villa = $_GET['villa'];
$sql = mysql_query("SELECT unavailable_date_from, unavailable_date_to FROM villa WHERE name = '".$villa."'");
$json = "[";
while($results = mysql_fetch_object($sql)){
foreach ($results a开发者_Go百科s $field => $value) {
$a = explode("-", $value);
$json = $json . '[' . $a[1] .','. $a[2] .'],';
}
$json = substr($json, 0, strlen($json)-1);
}
$json = $json . ']';
echo $json;
The current code give the following result: [[03,08],[03,10][03,15],[03,20]]
Can somebody tell me how can I add that one comma between the second and third array element
Thanks
Move $json = substr($json, 0, strlen($json)-1);
to be on the line before $json = $json . ']';
.
It will look like:
if ($json != '[') $json = substr($json, 0, strlen($json)-1);
$json = $json . ']';
Kind of messy, but it will work. Edit: Using rtrim
would be nicer:
$json = rtrim($json, ',');
$json = $json . ']';
Here's the full code:
$json = '';
while($results = mysql_fetch_object($sql)) {
foreach ($results as $field => $value) {
$a = explode("-", $value);
$json .= '[' . $a[1] .','. $a[2] .'],';
}
}
$json = '[' . rtrim($json,','). ']';
for example add this:
$json = str_replace('][', '],[', $json);
before last echo line.
The $json = substr($json, 0, strlen($json)-1);
should be after the loop finishes and before the ']'
addition.
include("db.php");
$villa = $_GET['villa'];
$sql = mysql_query("SELECT unavailable_date_from, unavailable_date_to FROM villa WHERE name = '".$villa."'");
$json = "[";
while($results = mysql_fetch_object($sql)){
foreach ($results as $field => $value) {
$a = explode("-", $value);
$json = $json . '[' . $a[1] .','. $a[2] .'],';
}
}
if (len($json) > 1) $json = substr($json, 0, strlen($json)-1);
$json = $json . ']';
echo $json;
精彩评论