PDO fetch array of arrays. Outer has numeric index

2019-08-29 07:17发布

问题:

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

回答1:

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