Notification texts go here Contact Us Buy Now!

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

Workaround for Zend_Db fetchAll() to Return Values as Keys

The Zend_Db fetchAll() method by default returns an array of associative arrays, with the keys being the column names and the values being the column values. However, there are situations where you may want to use the column values as the keys instead.

One way to achieve this is to use the following workaround:

$select = $this->db->select()->from('table_name'); $results = array(); foreach ($this->db->fetchAll($select) as $row) { $results[$row['column_name']] = $row; }

This workaround will create an array with the column values as the keys and the entire row as the values.

Alternative Solution Using array_column()

If you are using PHP 5.5 or later, you can use the array_column() function to achieve the same result in a more concise way:

$select = $this->db->select()->from('table_name'); $results = array_column($this->db->fetchAll($select), 'column_name');

This solution will create an array with the column values as the keys and the values being the values of the specified column.

Note:

It's important to note that this workaround will not work if the column values are not unique. In such cases, you will need to use a more complex solution, such as creating a temporary table or using a GROUP BY query.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.