Mônica R.
Mônica R.

Reputation: 225

Json Encode Multi dimension array format

im retrieving some data in my database table and than convert to json, but i need to create a array with this structire in my php loop

["postcode"=>"townName"...]

but instead is giving me

["postcode=>townName"...]

My code:

$sql = "SELECT * FROM uk_postcodes";
    $result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));

    $dname_list = array();
    while($row = mysqli_fetch_array($result))
    {

        $dname_list[] = $row['postcode']."=>".$row['town'];
    }
    echo json_encode($dname_list);

Upvotes: 2

Views: 30

Answers (1)

mishunika
mishunika

Reputation: 1916

In that line:

$dname_list[] = $row['postcode']."=>".$row['town'];

You're creating a string with "=>" in the middle (see string concatenation). You should specify the key of the array to be the postcode field, and the value - town field. Just change that line to:

$dname_list[$row['postcode']] = $row['town'];

http://php.net/manual/en/language.types.array.php

Upvotes: 1

Related Questions