Welcome Guest, Not a member yet? Register   Sign In
Populate drop down list from database
#7

[eluser]Kamarg[/eluser]
I often times will have need of multiple fields from a table for one use and two specific fields from the same result set for a select so I wrote the below function.
Code:
/**
     * Create an array with key/value pairs from an array of objects/arrays.
     *  
     * @author Daniel Razafsky
     * @param array - Array of objects/arrays to get keys and values from
     * @param object - The element(s) to use as keys. To use multiple values, seperate element names with |
     * @param object - The element(s) to use as values. To use multiple values, seperate element names with |. Passing null will assign the entire element to the returned array subelement.
     * @return array - The newly created array
*/
if(!function_exists('dropdown_array')) {
    function dropdown_array($array, $key, $value = null, $keep_empty_values = FALSE) {
        if(!is_array($array)) { $array = array($array); }
        $ret = array('' => ' ');
        
        $key     = explode('|', $key);
        $value     = is_null($value) ? null : explode('|', $value);
        
        foreach($array as $item) {
            $bInclude = TRUE;
            $item = (array) $item;
            
            // Build the key
            $key_val = '';
            foreach($key as $k) {
                if(!isset($item[$k])) { $bInclude = FALSE; }
                else { $key_val .= $item[$k] . ' - '; }
            }
            $key_val = substr($key_val, 0, strlen($key_val) - 3);
            
            // Build the value
            $value_val = '';
            if(!is_null($value)) {
                foreach($value as $v) {
                    if(!isset($item[$v])) { $bInclude = FALSE; }
                    else { $value_val .= $item[$v] . ' - '; }
                }
            }
            $value_val = substr($value_val, 0, strlen($value_val) - 3);
            
            if($bInclude && $keep_empty_values || is_null($value) || !empty($value_val)) {
                $ret[$key_val] = !is_null($value) ? $value_val : $item;
            }
        }
        
        return $ret;
    }
}

Using this I can do a select * on my table and still easily build an array for my select without having to write a foreach or a new function every time.


Messages In This Thread
Populate drop down list from database - by El Forum - 09-02-2010, 08:27 AM
Populate drop down list from database - by El Forum - 09-02-2010, 08:52 AM
Populate drop down list from database - by El Forum - 09-02-2010, 10:09 AM
Populate drop down list from database - by El Forum - 09-02-2010, 11:34 AM
Populate drop down list from database - by El Forum - 09-02-2010, 11:43 AM
Populate drop down list from database - by El Forum - 09-02-2010, 11:58 AM
Populate drop down list from database - by El Forum - 09-02-2010, 12:14 PM



Theme © iAndrew 2016 - Forum software by © MyBB