简体   繁体   中英

PDO fetch array of arrays. Outer has numeric index. Inner has associative index

Am working on a database of student lessons and answers. Each assignment and each result has an associative array with six or more fields (columns) stored in a MySQL database in lesson and answer tables.

I use sql PDO execute() to get all the assignments and also different sql to get all the results.

FetchAll gives me an outer numeric array and an inner array with both numeric and associative indexes. I want only associative indexes on the inner array. ->fetch(\\PDO::FETCH_ASSOC); gives me nothing. (the \\ due to name spaces -- without the \\ I get an error) ->fetchAll(); gives me an outer numeric index array and the inner arrays with both indexes.

I can strip out the inner numeric indexes or ignore them, but that seems klutzy as these inner arrays are used many ways.

Perhaps the answer is in the sql instead of the fetch. The best I have come up with so far is stripping out the numeric indexes with:

    $stmt->execute();
    $rows = $stmt->fetchAll();
    foreach ($rows as $key=>$value) {
        foreach ($value as $key2=>$value2) {
            if (is_numeric($key2) === TRUE) {
                unset($value[$key2]);
            }
        }
        $rows[$key] = $value;
    }
    return $rows;

Is there a better way?

jimfuqua

With help from Michael Berkowski's comment, I tried an experiment.

With $rows = $stmt->fetchAll(\\PDO::FETCH_ASSOC); I got just what I was looking for. The outer array had a numeric index and the inner array had an associative index.

With $rows = $stmt->fetchAll(); I got the duplication I was trying to avoid.

With $rows = $stmt->fetch(\\PDO::FETCH_ASSOC); I got one of the inner arrays as associative only. There was no outer array and one of the inner arrays was missing. Because they were identical, I could not tell which inner array was lost.

JimFuqua

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