0

Imagine that you have to query the database in order to retrieve some data (in this example names and ages):

while ($submission = db_fetch_array($submissions)) {
  $data[] = $submission['data'];
}

So the resulting dump of the $data array would be something like:

Array
(
  [0] = "John"
  [1] = "33"
)

If I wanted to form descriptive keys, the resulting code would be:

while ($submission = db_fetch_array($submissions)) {
  $data[] = $submission['data'];
}

$data['name'] = $data[0];
$data['age'] = $data[1];

Now if instead of only two fields in my array I would have 10 or more fields, this seems to me a little bit redundant.

Is there a more logical way to do this?

Note: db_fetch_array it's a drupal abstraction in order to fetch a query as an array

1 Answer 1

1

Don't now, what db_*() should be, but I recommend to fetch the array as associative array direct from the database

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
  $data[] = $row;
}

This results in an array of associative arrays, where the keys of the inner associative arrays are the name of the columns.

http://php.net/pdostatement.fetch

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

3 Comments

I forgot to say it, but db_fetch_array it's a drupal abstraction in order to fetch a query as an array. I can't do it like you pointed out because the field name is always "data", using a query with INNER JOIN I retrieve all the "data" of a single entity (in the example Person).
You should refer the drupal documentation, because I suspect, that they provide similar functionality.
You are right, but the same functionality doesn't work in this case, because the field name in the DB is always "data", so all the array keys would be also named "data".

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.