This line of code adds two array values into $carRate variable:
array_push($carRate,array($row['rental_type_value'],$row['rental_by_value']));
public function selectRate()
{
$sql="SELECT * FROM rental_by, rental_type WHERE rental_by.rental_type_id=rental_type.rental_type_id";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$carRate=array();
while($row = $stmt->fetch())
{
array_push($carRate,array($row['rental_type_value'],$row['rental_by_value']));
}
return $carRate;
}
我在另一个页面中调用上面的函数,如:
$setting = new setting();
$selectRate=$setting->selectRate();
$json=array();
array_push($json,array("type"=>$carType,"maker"=>$carMaker,"rate"=>$selectRate));
echo json_encode($json);
在jquery之后显示通过ajax获取数据后,在成功函数内部显示:
if(data && data[0].rate) {
/*for(var c in data[0].maker) {
makers += c + ', ';
}*/
rates +="<table>";
$.each(data[0].rate , function( index, value ){
console.log(value);
rates +="<tr><td>"+ value[0] +"</td><td> : </td><td>"+ value[1] +"</td></tr>";
});
rates +="</table>";
}
$('#elementForRates').html(rates && rates.trim().replace(/,$/, "") + "." || 'No Rate data available');
JSON输出:
["rental_days", "78"]
["rental_days", "56"]
["rental_days", "34"]
["rental_hour", "45"]
["rental_hour", "67"]
["rental_hour", "23"]
["rental_hour", "45"]
["rental_hour", "67"]
此输出如下:
rental_days:78
rental_days:56
rental_days:34
rental_hour:45
rental_hour:67
rental_hour:23
rental_hour:45
rental_hour:67
期望的结果:
rental_days:78,56,34
rental_hour:45,67,23,45,67
有没有办法按照php本身的值对rental_type_value和租借进行分类/排序?
答案 0 :(得分:1)
假设数据返回如下:
var data = [
['rental_days', '78'],
['rental_hour', '67'],
['rental_days', '56'],
['rental_hour', '45'],
['rental_days', '34'],
['rental_hour', '23'],
['rental_hour', '45'],
['rental_hour', '67']];
您可以对数据客户端进行分类:
var categorized = {};
data.forEach(function(d){
if(!!categorized[d[0]]){
categorized[d[0]].push(d[1]);
} else {
categorized[d[0]] = [d[1]];
}
});
并将行添加到表中,如下所示:
for (var c in categorized) {
$('table tr:last').after('<tr><td>' + c + '</td><td>' + categorized[c].join() + '</td></tr>');
};
看看这个fiddle