【问题标题】:Problems with sorting an array, json_encode排序数组的问题,json_encode
【发布时间】:2016-09-26 03:25:02
【问题描述】:

我在对数组进行排序时遇到问题。我试图用 json 返回我用 ksort 排序的数组,看起来数组排序很好,但是当我用 json 返回它时,它变成了真实状态。

代码如下:

$sql = mysql_query("select e.id_equip,e.nom from Equips e inner    join Competicions c on e.id_competicio=c.id_competicio where c.nom='Preferent' and c.actiu=1");

$tempArray = array();
$json = array();

while($row = mysql_fetch_assoc($sql)){

$sqlDadesLocal = mysql_query("Select SUM(case when resultat_total_local >= 4 then 1 else 0 end) as partitsGuanyats, SUM(case when resultat_total_local < 4 then 1 else 0 end) as partitsPerduts, SUM(resultat_parcial_local) as jocsAFavor, SUM(resultat_parcial_visitant) as jocsEnContra from Actes where id_equip_local = '".$row['id_equip']."'");
$DadesLocal = MySQL_fetch_row($sqlDadesLocal);

$sqlDadesVisitant =  mysql_query("Select SUM(case when resultat_total_visitant >= 4 then 1 else 0 end) as partitsGuanyats, SUM(case when resultat_total_visitant < 4 then 1 else 0 end) as partitsPerduts, SUM(resultat_parcial_visitant) as jocsAFavor, SUM(resultat_parcial_local) as jocsEnContra from Actes where id_equip_visitant = '".$row['id_equip']."'");
$DadesVisitant = MySQL_fetch_row($sqlDadesVisitant);

$SumaPartitsGuanyats = $DadesLocal[0]+$DadesVisitant[0];
$SumaPartitsPerduts = $DadesLocal[1]+$DadesVisitant[1];
$SumaJocsAFavor = $DadesLocal[2]+$DadesVisitant[2];
$SumaJocsEnContra = $DadesLocal[3]+$DadesVisitant[3];
$DiferenciaJocs = $SumaJocsAFavor-$SumaJocsEnContra;
$Punts = $SumaPartitsGuanyats*2;

$json['nomEquip'] = $row['nom'];
$json['partitsGuanyats'] = $SumaPartitsGuanyats;
$json['partitsPerduts'] = $SumaPartitsPerduts;
$json['jocsAFavor'] = $SumaJocsAFavor;
$json['jocsEnContra'] = $SumaJocsEnContra;
$json['diferenciaJocs'] = $DiferenciaJocs;
$json['puntsTotals'] = $Punts;

$tempArray[]= $json;
}

ksort($tempArray,$tempArray['puntsTotals']);

echo json_encode(array('preferent'=>$tempArray));

mysql_close($conn);
}
?>

【问题讨论】:

标签: php android arrays json sorting


【解决方案1】:

解决了更改函数 ksort 的问题,效果很好。

usort($tempArray, function($a, $b) {
        if($a['puntsTotals']==$b['puntsTotals']) return 0;
        return $a['puntsTotals'] < $b['puntsTotals']?1:-1;
});


echo json_encode(array('preferent'=>$tempArray));

【讨论】:

    猜你喜欢
    • 2013-02-23
    • 2011-09-27
    • 2021-01-27
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 2010-12-03
    • 2014-02-08
    相关资源
    最近更新 更多