0

So whenever I download data from my mysql database, and convert to a JSON array via PHP then display it, I get duplicated values.

I do understand why this is so, but is there any way to remove the numeric duplicates?:/

{"id":"1","0":"1","userId":"23","1":"23","message":"HELLO","2":HELLO"},
{"id":"2","0":"2","userId":"53","1":"53","message":"WOW","2":WOW"}
3
  • Looks like you're using the default "both" fetch option. You need to specify associative only. Is it PDO or mysqli? Commented Mar 9, 2018 at 17:35
  • 1
    Please show your code Commented Mar 9, 2018 at 17:36
  • Open a manual for database api you use and find answer there. Commented Mar 9, 2018 at 17:39

2 Answers 2

1

For PDO use PDO::FETCH_ASSOC flag after query execute

$sth = $dbh->prepare("SELECT col FROM table");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);

And for mysql_* functions:

$query = "SELECT col FROM table";
$result = mysqli_query($connection, $query);
$output = array();
while($row = mysqli_fetch_assoc($result)){
    $output[] = $row;
}
json_encode($output);
Sign up to request clarification or add additional context in comments.

Comments

0

As you've asked, to remove it: Loop through it, if key is numeric delete.

foreach($array as $key=>$var){ 
    if(is_numeric($key)){ 
        delete $array[$key]; 
    } 
} 

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.