Osvaldo Mercado
Osvaldo Mercado

Reputation: 971

Zend_Db fetchAll() to return values as keys, not as key => value

Is there a way to change the default functionality in Zend_Db fetchall() method, so that it doesn't return this:

[0] => 100000055944231
[1] => 100000089064543
[2] => 100000145893011
[3] => 100000160760965

but this:

[100000055944231]
[100000089064543]
[100000145893011]
[100000160760965]

Upvotes: 1

Views: 3861

Answers (3)

Fabien Haddadi
Fabien Haddadi

Reputation: 2080

Further to Pieter's, I'd add the case where the rows are themselves arrays, and not just scalars; it's possible to nest the results, to as many fields as the query contains.

e.g. Here with two levels of nesting, respectively on field1 and field2.

$complex_results = array_map(function($row) { return array($row['field1'] => array($row['field2'] => $row)); }, $results);

As always, each row contains all fields, but $complex_results is indexed by field1, then field2 only.

Upvotes: 0

Pieter
Pieter

Reputation: 1774

Although your question is actually flawed (noted by BartekR), I suppose you're trying to receive a simple array, instead of a multidimensional one.

You could do:

$results = $this->db->fetchAll($select);
$values = array_map(function($row) { return $row['column']; }, $results);

This will turn:

array(
    array('column' => 'test'),
    array('column' => 'test2'),
    array('column' => 'test3'),
);

into

array(
    'test',
    'test2',
    'test3'
);

(note; my example only works in PHP5.3+, if you're working with PHP5.2, you can define the function and use it by its name with array_map (e.g. array_map('methodName', $results))

Upvotes: 2

Mrmartin
Mrmartin

Reputation: 105

I'm looking for a similar solution, I'm trying to load a field returned by the fetchAll($select) as the array key.. Without looping through the entire resultset.

So:

$results = $this->db->fetchAll($select, <FIELDNAME_TO_MAKE_KEY_OF_RESULTS_ARRAY>);

results[<my fieldname>]->dbfield2;

Upvotes: 0

Related Questions