如何提取PHP JSON数组名称


How Do I Extract a PHP JSON Array Name

我有一个PHP文件,它返回一个JSON数组。我需要提取数组名称,在本例中为*Regulatory_Guidance_Library*,jQuery作为函数$('#navHeaderTitle').text(arrayName);的var。我不知道这是怎么做到的。

感谢您的帮助

我在HTML文档中的功能:

function loadNav(url, container, appendE) {
        $.getJSON(url, function(data){
                    var arrayName = "";
            $.each(data.Regulatory_Guidance_Library, function(){
                var newItem = $('#' + container).clone();
                // Now fill in the fields with the data
                newItem.find("h1").text(this.label);
                newItem.find("h2").text(this.title);
                newItem.find("p").text(this.description);
                // And add the new list item to the page
                newItem.children().appendTo('#' + appendE)
            });
            $('#navHeaderTitle').text(arrayName);
            //transition(pageName, "show");
        });
    };

提供的PHP:

<?php
//MySQL Database Connect
include 'andaerologin.php';
mysql_select_db("andaero");
$sql=mysql_query("select * from regulatory_list");
$output = new stdClass();
while($row = mysql_fetch_assoc($sql)) {
    $output->Regulatory_Guidance_Library[] = $row;
}
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
echo (json_encode($output));
mysql_close();
?>

修改php:

$output = array();
  /* used "key" as name...could change to suit your app*/
$output['key']='Regulatory_Guidance_Library';
while($row = mysql_fetch_assoc($sql)) {
    $output['items'][]= $row;
}

AJAX:

$.getJSON(url, function(data){
        $.each(data.items, function(){
            var newItem = $('#' + container).clone();
            // Now fill in the fields with the data
            newItem.find("h1").text(this.label);
            newItem.find("h2").text(this.title);
            newItem.find("p").text(this.description);
            // And add the new list item to the page
            newItem.children().appendTo('#' + appendE)
        });
        $('#navHeaderTitle').text(data.key);
        //transition(pageName, "show");
    });

另一个答案可能更有用,但如果你想用javascript获取对象属性的名称,你可以这样做:

for (var name in data) {
    alert(name);
}

在你的情况下,由于你只有一处房产可以做:

for (var name in data) {
    $('#navHeaderTitle').text(name);
}