将具有相同值的列分组为一行(JSON输出)


Group Column With Same Value Into One Row (JSON Output)

我使用PHP输出一些SQL代码,然后将JSON中的数据返回到Ajax,然后从中填充下拉列表。其想法是,如果数据在半径内,则电缆编号下拉列表会显示多个选项,但我遇到的问题是,如果在该半径内有6个选项,则会显示相同的值,如6次。。。例如,应该发生的情况是,具有1、2、3、4和5段的电缆编号1000和具有1、3、3和4段的电缆号1001在50英尺半径内,因此只有电缆号1000和1001应该在下拉列表中,并且段号的处理方式不同(与此问题无关)。。。问题是下拉列表将显示电缆编号1000五次(与DB中该电缆编号的截面编号一样多),1001电缆编号也显示四次,所以现在我在下拉列表中有9个电缆编号,都是相同的编号。我如何才能让我的php/sql只显示两个电缆编号,而不显示9次?

我认为这种行为的罪魁祸首是因为HAVING DISTANCE和半径都不同,所以由于有不同的距离列,所以每行的距离都用相同的电缆编号填充。。。

SQL

// Define JSON array
$array = array();
$sql = <<<EOD
SELECT DISTINCT cable_no,
       3959.0 * 5280.0 * acos(sin(radians($lat)) * sin(radians(extraction_worksheet.mh_lat_a))
       + cos(radians($lat)) * cos(radians(extraction_worksheet.mh_lat_a))
       * cos(radians(extraction_worksheet.mh_long_a) - radians($lon))) as distance
 FROM extraction_worksheet
 WHERE extraction_worksheet.mh_lat_a != ''
 HAVING distance <= $radius
EOD;
$result = mysql_query($sql) or die ('Error'.mysql_error());
// If DB query successful then send data to calling routine.
    while ($row = mysql_fetch_array($result)) {
        $array[] = $row;
    }   
        print json_encode($array);

JS-

function populate_cableno(latitude, longitude, radius) {
$.ajax({
    type: 'GET',
    url: './php/getcable_number.php',
    data: 'latitude=' + latitude + '&longitude=' + longitude + '&radius=' + radius,
    dataType: 'json',
    success: function (mydata) {
        if (mydata.length >= 1) {
            if (mydata.length > 1) {
                $("#cable_no")
                    .replaceWith('<select onchange="get_co_name(); get_section_no(); return false;" id="cable_no" name="cable_no"></select>');
                var combo = document.getElementById("cable_no");
                while (combo.firstChild) {
                    combo.removeChild(combo.firstChild);
                };
                var option = document.createElement("option");
                for (var i = 0; i < mydata.length; i++) {
                    option = document.createElement("option");
                    option.text = mydata[i]['cable_no'];
                    option.value = mydata[i]['cable_no'];
                    try {
                        combo.add(option, null); //Standard
                    } catch (error) {
                        combo.add(option); // IE only
                    }
                };
                get_co_name();
                get_section_no();
            }
            else {
                document.forms['prepform'].elements['cable_no'].value = mydata[0]['cable_no'];
                get_co_name();
                get_section_no();
            }
        } else {
            alert("There are no cables within a 2000ft radius.");
        }
    },
    error: function () {
        alert("Error...");
    },
    complete: function () {}
});
};

好吧,我最终发现,在有距离之前添加"GROUP BY cable_no"才是诀窍。谢谢