简体   繁体   中英

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.

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:

<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:

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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