简体   繁体   中英

PHP Array duplicates: every string key has numeric key

I'm trying to get an array with utf-8 values from an MS-SQL query.

Nearly everything works fine, except that the result array looks like this:

Array (
 [id] => 1;
 [0] => 1; // this is redundant
 [countryName] => england;
 [1] => england; // this is redundant
)

I don't want the duplicate numeric keys. Why are they even created? The code which is leading to this result is:

# execute the query
foreach ($pdoConnection->query($sqlStatement) as $row) {
   // encode row in utf8 so json works and save row in array
   $output[] = array_map('utf8_encode', $row);
}

Thanks for any idea how that can be solved.

You need to fetch as associative . Follow this example:

$stmt = $this->db->prepare('SELECT title, FMarticle_id FROM articles WHERE domain_name =:domain_name');
$stmt->bindValue(':domain_name', $domain);
$stmt->execute();
$article_list = $stmt->fetchAll(PDO::FETCH_ASSOC);

Reference: PDOStatement::fetchAll

Try replacing this line,

foreach ($pdoConnection->query($sqlStatement, PDO::FETCH_ASSOC) as $row)

That flag is for getting associative records.

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