简体   繁体   English

将php关联数组解析为javascript对象

[英]Parse php associative array to javascript object

I want to have a javascript array of "country" objects which at this stage will have only two attributes: name, and geonameId. 我想拥有一个“国家”对象的javascript数组,该对象在此阶段将仅具有两个属性:name和geonameId。

I get these countries from a database like so: 我从这样的数据库中获得这些国家:

            $sql = "SELECT name, geonameId FROM countryinfo";
            $result = $conn->query($sql);
            if ($result->num_rows > 0) {
                $rows = array ();
                while($row = $result->fetch_assoc()) {
                    $country["geonameId"]);
                    $rows[$row['geonameId']] = $row['name'];
                }
            }
            $conn->close();
        ?>

I then have this javascript script which turns the php array into a javascript one: 然后,我有了这个javascript脚本,它将php数组变成了javascript:

<script type="text/javascript">
    var allCountries = <? echo json_encode($rows); ?>;
    console.log(allCountries);
</script>

I just want to turn that array of key/value pairs into an array of objects so I have easier access to new attributes that I may add in the future. 我只想将键/值对的数组转换为对象的数组,以便可以更轻松地访问将来可能添加的新属性。 At the moment the javascript array logs to the console like this: 目前,javascript数组以如下方式登录到控制台:

Object {0: "Netherlands Antilles", 49518: "Rwanda", 51537: "Somalia", 69543: "Yemen", 99237: "Iraq", 102358: "Saudi Arabia", 130758: "Iran", 146669: "Cyprus", 149590: "Tanzania", 163843: "Syria", 174982: "Armenia", 192950: "Kenya", 203312:...

How do I convert that array of key/value pairs to an array from javascript objects (with refactoring, I will be adding a Country class and the array will contain Country objects). 如何将键/值对的数组从javascript对象转换为数组(通过重构,我将添加一个Country类,并且该数组将包含Country对象)。

My relevant code was changed to this to get it to work: 我的相关代码已更改为此,以使其正常工作:

$sql = "SELECT name, geonameId FROM countryinfo";
    $result = $conn->query($sql);
    $allCountries = [];
    if ($result->num_rows > 0) {
        $rows = array ();
        while($row = $result->fetch_assoc()) {
            $country = array(
                "name" => $row['name'],
                "geonameId" => $row['geonameId']
            );
            $allCountries[] = $country;
        }
    }
    $conn->close();
?>
<script type="text/javascript">
    var allCountries = <?php echo json_encode($allCountries, JSON_PRETTY_PRINT) ?>;
    console.log(allCountries)
</script>

在PHP端简单地序列化为JSON,然后在Javascript中执行JSON.parse

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM