0

I'm playing with JSON using PHP. I'm using json_encode() function to create JSON. Hovewer I've got strange JSON output:

[

    {
        "0": "1",
        "1": "test",
        "2": "test",
        "ID": "1",
        "title": "test",
        "imageUrl": "test"
    },
    {
        "0": "2",
        "1": "welcome",
        "2": "http://overkiller.pl/Smokopedia/Images/01.jpg",
        "ID": "2",
        "title": "welcome",
        "imageUrl": "http://overkiller.pl/Smokopedia/Images/01.jpg"
    }

]

Why I am getting this sort JSON how to get rid these numbers from it? My PHP code:

<?php
    header('Content-type: application/json');
    $connection = mysql_connect('localhost', 'root', 'sam1');
    $array = array();
    if($connection)
    {
        mysql_select_db("Smokopedia");
        $result = mysql_query("Select * from mainMenu");
        if($result)
        {
            while ($row = mysql_fetch_array($result)) 
            {
                array_push($array, $row);
            }
            echo json_encode($array);
        }else
        {
            $errorJson = array(
                    message => 'Result is empty or incorrect',
                    type => 'error'
                );
            echo json_encode($errorJson);
        }
    }
    mysql_close();

?>

2 Answers 2

5

mysql_fetch_array includes both numeric indexed keys and column name indexed keys.

Change it to mysql_fetch_assoc and you'll get the end result you need.


Note though, that the entire mysql extension is deprecated and you should consider switching to PDO or Mysqli.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I've forgot about that function in PHP.
2

The issue is you are fetching an array, which includes both numerical indexes and string keys.

Change to mysql_fetch_assoc

while ($row = mysql_fetch_ssoc($result)) 

Side note: the mysql_* library is deprecated. Considered upgrading to a modern API such as MySQLi or PDO.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.