Location: PHPKode > scripts > iviArray > iviarray/iviArray.class.php
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4.3                                                      |
// +----------------------------------------------------------------------+
// | Copyright (c) 2003 Moritz Geselle                                    |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license,       |
// | that is bundled with this package in the file LICENSE, and is        |
// | available through the world-wide-web at                              |
// | http://www.php.net/license/2_02.txt.                                 |
// | If you did not receive a copy of the PHP license and are unable to   |
// | obtain it through the world-wide-web, please send a note to          |
// | hide@address.com so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Author: Moritz Geselle <hide@address.com>                          |
// +----------------------------------------------------------------------+
//
// $Id: iviArray.php, v0.5 2003/08/01 $
//
// Encapsulation and unification of PHP array functions.
//

class iviArray
{
    var $_array;
    
    /**
    * iviArray::iviArray()
    * 
    * Creates an instance of iviArray (constructor)
    * 
    * @param mixed $init - initial values (array or iviArray object)
    */    
    function iviArray($init = array())
    {
        $this->set($init);
    }
    
    /**
    * iviArray::toArray()
    * 
    * Returns a reference of the internal array
    * 
    * @return array
    */
    function &toArray()
    {
        return $this->_array;
    }
    
    /**
    * iviArray::toString()
    * 
    * Returns a string containing the array values seperated by the specified seperator
    * (see http://www.php.net/manual/en/function.implode.php)
    * 
    * @param string $seperator - seperator to be put between the elements
    * @return string           - a string containing all array values seperated by the specified seperator
    */
    function toString($seperator = ',')
    {
        return implode($seperator, $this->_array);
    }
    
    /**
    * iviArray::fromString()
    * 
    * Returns an array containing elements from the given string seperated by the given seperator
    * (see http://www.php.net/manual/en/function.explode.php)
    * 
    * @param string $str       - given string containing array elements
    * @param string $seperator - seperator of the elements in $str
    * @param int    $limit     - if specified, maximum number of elements is set to $limit
    * @return array            - array created from $str
    */
    function fromString($str, $seperator = ',', $limit = null)
    {
        if (is_null($limit)) {
            return explode($seperator, $str);
        }
        else {
            return explode($seperator, $str, $limit);
        }
    }
    
    /**
    * iviArray::parseString()
    * 
    * Sets local array to the elements given in $str
    * (see http://www.php.net/manual/en/function.explode.php)
    * 
    * @param string $str       - given string containing array elements
    * @param string $seperator - seperator of the elements in $str
    * @param int    $limit     - if specified, maximum number of elements is set to $limit
    */
    function parseString($str, $seperator = ',', $limit = null)
    {
        $arr = $this->fromString($str, $seperator, $limit);
     
        if (is_array($arr)) {
            $this->_array = $arr;
        }
    }
    
    /**
    * iviArray::fromFile()
    * 
    * Read file into array (see http://www.php.net/manual/en/function.file.php)
    * 
    * @param string $file - name of the file to read
    */
    function fromFile($file)
    {
        $arr = file($file);
     
        if (is_array($arr)) {
            $this->_array = $arr;
        }
    }
    
    /**
    * iviArray::get()
    * 
    * Get a value at specified position (multiple keys or an array of keys can be passed for accessing multi-dimensional arrays)
    * e.g.: $array->get(12, 3, 5) is similar to $array[12][3][5]
    *       $array->get(array(12, 3, 5)) is similar to $array[12][3][5]
    * 
    * @param mixed $keys - key(s) of the element to return
    * @return mixed      - value of the specified element - false otherwise
    */
    function get()
    {
        if (func_num_args() < 1) {
            return false;
        }
        
        $keys = func_get_args();
        
        if ((func_num_args() == 1) && (is_array($keys[0]))) {
          $keys = $keys[0];
        }
        
        $keyStr = '';
        
        foreach ($keys as $key) {
          $keyStr .= '[\'' . $key . '\']';
        }
        
        return eval('return $this->_array' . $keyStr . ';');
    }
    
    /**
    * iviArray::add()
    * 
    * Adds / replaces a value at the specified key
    * 
    * @param mixed $key - the key at which the value should be added / replaced
    * @param mixed $val - the value to add / replace
    */
    function add($key, $val)
    {
        $this->_array[$key] = $val;
    }
    
    /**
    * iviArray::append()
    * 
    * Appends a value at the end of the array
    * 
    * @param mixed $val - value tu append
    */
    function append($val)
    {
        $this->_array[] = $val;
    }
    
    /**
    * iviArray::prepend()
    * 
    * Prepends a value at the beginning of the array
    * 
    * @param mixed $val - value to prepend
    */
    function prepend($val)
    {
        array_unshift($this->_array, $val);
    }
    
    /**
    * iviArray::remove()
    * 
    * Removes an element from the array
    * 
    * @param $key - key of the element to be removed
    */
    function remove($key)
    {
        unset($this->_array[$key]);
    }
    
    /**
    * iviArray::alter()
    * 
    * Alias for iviArray::add()
    * 
    * @param $key
    * @param $val
    */
    function alter($key, $val)
    {
        $this->add($key, $val);
    }
    
    /**
    * iviArray::merge()
    * 
    * Merges given array or iviArray with this array
    * 
    * @param mixed $array - array or iviArray to be merged with this array
    */
    function merge($array)
    {
        if (is_array($array)) {
            $this->_array = array_merge($this->_array, $array);
        }
        elseif ((is_object($array)) && (is_a($array, 'iviArray'))) {
            $this->_array = array_merge($this->_array, $array->toArray());
        }
    }
    
    /**
    * iviArray::set()
    * 
    * Set this array to given array or iviArray
    * 
    * @param $array - array or iviArray which contains the values to be set
    */
    function set($array)
    {
        if (is_array($array)) {
            $this->_array = $array;
        }
        elseif ((is_object($array)) && (is_a($array, 'iviArray'))) {
            $this->_array = $array->toArray();
        }
    }
    
    /**
    * iviArray::equals()
    * 
    * Check whether the array or iviArray given in $array equals to the local array
    * 
    * @param $array - the array to be compared
    * @return 
    */
    function equals($array)
    {
        if (is_array($array)) {
            return count(array_diff_assoc($this->_array, $array)) == 0;
        }
        elseif ((is_object($array)) && (is_a($array, 'iviArray'))) {
            return count(array_diff_assoc($this->_array, $array->_array)) == 0;
        }
    }
    
    /**
    * iviArray::reverse()
    * 
    * Reverses array's order
    * 
    * @param bool $preserve - whether to preserve key associations or not (default is true)
    */
    function reverse($preserve = true)
    {
        $this->_array = array_reverse($this->_array, $preserve);
    }
    
    /**
    * iviArray::flip()
    * 
    * Flip keys and values (see http://www.php.net/manual/de/function.array-flip.php)
    * 
    */
    function flip()
    {
        $this->_array = array_flip($this->_array);
    }
    
    /**
    * iviArray::chunk()
    * 
    * Split an array into chunks (see http://www.php.net/manual/de/function.array-chunk.php)
    * 
    * @param int $size      - chunk size
    * @param bool $preserve - whether to preserve key associations or not (default is true)
    */
    function chunk($size, $preserve = true)
    {
        $this->_array = array_chunk($this->_array, $size, $preserve);
    }
    
    /**
     * iviArray::pad()
     * 
     * Pad the array to a certain size (see http://www.php.net/manual/en/function.array-pad.php)
     * 
     * @param int $size    - the size the array shall be padded to
     * @param mixed $value - the value to which the new elements are set to
     */
    function pad($size, $value)
    {
        $this->_array = array_pad($this->_array, $size, $value);
    }
    
    /**
     * iviArray::shuffle()
     * 
     * Shuffles the array. (see http://www.php.net/manual/en/function.shuffle.php)
     * Should be optimized!
     * 
     */
    function shuffle()
    {
        srand((float)microtime() * 1000000);
        shuffle($this->_array);
    }
    
    /**
     * iviArray::fill()
     * 
     * Fills an array with $amount entries of the value of $value, keys starting at $start.
     * (see http://www.php.net/manual/en/function.array-fill.php)
     * 
     * @param int $start   - starting index
     * @param int $amount  - amount of elements (must be > 0)
     * @param mixed $value - value of the elements
     */
    function fill($start, $amount, $value)
    {
        $this->_array = array_fill($start, $amount, $value);
    }
    
    /**
     * iviArray::range()
     * 
     * Set the array from $low to $high, inclusive. If $low > $high, the sequence will be from $high to $low. 
     * (see http://www.php.net/manual/en/function.range.php)
     * 
     * @param int $low  - start index
     * @param int $high - end index
     * @param int $step - step size (default is 1)
     */
    function range($low, $high, $step = 1)
    {
        $this->_array = range($low, $high, $step);
    }
    
    /**
    * iviArray::reIndex()
    * 
    * Redistributes indices (converts keys to ascending numbers)
    * 
    */
    function reIndex()
    {
        $this->_array = array_values($this->_array);
    }
    
    /**
    * iviArray::removeDuplicates()
    * 
    * Removes all duplicate values of the array (see http://www.php.net/manual/en/function.array-unique.php)
    *     
    */
    function removeDuplicates()
    {
        $this->_array = array_unique($this->_array);
    }
    
    /**
    * iviArray::replace()
    * 
    * Replaces values given in $search with values given in $replace (see http://www.php.net/manual/en/function.str-replace.php)
    * 
    * @param mixed $search      - string(s) to be replaced
    * @param mixed $replacement - string(s) to replace with
    */
    function replace($search, $replacement)
    {
        $this->_array = str_replace($search, $replacement, $this->$this->_array);
    }
    
    /**
    * iviArray::changeKeyCase()
    * 
    * Changes array's keys case to either upper or lower case
    * (see http://www.php.net/manual/de/function.array-change-key-case.php)
    * 
    * @param int $case - case to that the keys should be changed to. possible values:  CASE_LOWER or CASE_UPPER
    */
    function changeKeyCase($case = CASE_LOWER)
    {
        $this->_array = array_change_key_case($this->_array, $case);
    }
    
    /**
    * iviArray::preg()
    * 
    * Perform a regular expression function on the array (search or replace)
    * (see http://www.php.net/manual/de/function.preg-replace.php
    *      http://www.php.net/manual/de/function.preg-grep.php)
    *      http://www.php.net/manual/de/function.preg-replace-callback.php
    * 
    * @param string $pattern    - regular expression search pattern 
    * @param string $type       - type of function. possible values: "search", "replace", "callback" (default is "search")
    * @param mixed $replacement - replacement value(s) when using "replace" respectively the name of the callback function when using "callback"
    * @param int $limit         - limit when using "replace" (default is -1 meaning "replace all")
    * @return array             - "search" results
    */
    function preg($pattern, $type = 'search', $replacement = '', $limit = -1)
    {
        if ($type == 'search') {
            return preg_grep($pattern, $this->_array);
        }
        elseif ($type == 'replace') {
            $this->_array = preg_replace($pattern, $replacement, $this->_array, $limit);
        }
        elseif ($type == 'callback') {
            $this->_array = preg_replace_callback($pattern, $replacement, $this->_array, $limit);
        }
    }
    
    /**
    * iviArray::sort()
    * 
    * Sort array by specified conditions
    * 
    * @param string $type  - sort type. possible values: 
    *                        "values"  - sort by values
    *                        "keys"    - sort by keys
    *                        "natural" - use natural sort (see http://www.php.net/manual/en/function.natsort.php)
    *                        "user"    - use user defined function to sort (see http://www.php.net/manual/en/function.usort.php)
    * 
    * @param array $params - array of sort parameters. possible values:
    *                        $params["reverse"]  - whether to sort in reverse order or not. default is false.
    *                        $params["keys"]     - whether to preserve key associations or not. default is false.
    *                        $params["flag"]     - modifies sorting behaviour (see http://www.php.net/manual/en/function.sort.php). default is SORT_REGULAR.
    *                        $params["case"]     - whether natural sort should be case sensitive or not. default is false.
    *                        $params["user"]     - "values" or "keys" - defines sort type for user defined functions (if type is set "user"). default is "values".
    *                        $params["function"] - name of the user defined function which is used for sorting if type is set to "user"
    */
    function sort($type = 'values', $params = array())
    {
        if (!isset($params['reverse'])) {
            $params['reverse'] = false;
        }
        
        if (!isset($params['keys'])) {
            $params['keys'] = false;
        }
        
        if (!isset($params['flag'])) {
            $params['flag'] = SORT_REGULAR;
        }
        
        if (!isset($params['case'])) {
            $params['case'] = false;
        }
        
        if (!isset($params['user'])) {
            $params['user'] = 'values';
        }
        
        switch ($type) {
            case 'values': 
                switch ($params['reverse']) {
                    case false: 
                        switch ($params['keys']) {
                            case false: sort($this->_array, $params['flag']); break;
                            case true:  asort($this->_array, $params['flag']); break;
                        }
                        break;
             
                    case true:                     
                        switch ($params['keys']) {
                            case false: rsort($this->_array, $params['flag']); break;
                            case true:  arsort($this->_array, $params['flag']); break;
                        }
                        break;
                }
                break;
            
            case 'keys':
                switch ($params['reverse']) {
                    case false: ksort($this->_array, $params['flag']); break;
                    case true:  krsort($this->_array, $params['flag']); break;
                }
                break;
         
            case 'natural':
                switch ($params['case']) {
                    case false: natcasesort($this->_array); break;
                    case true:  natsort($this->_array); break;
                }
         
                if ($params['reverse']) {
                    $this->reverse(true);
                }
         
                if (!$params['keys']) {
                    $this->reIndex();
                }
         
                break;
            
            case 'user': 
                switch ($params['user']) {
                    case 'values': 
                        switch ($params['keys']) {
                            case false: usort($this->_array, $params['function']); break;
                            case true:  uasort($this->_array, $params['function']); break;
                        }
                        break;
             
                    case 'keys': uksort($this->_array, $params['function']); break;
                }
                break;
        }
    }
    
    function getValueCount()
    {
        return array_count_values($this->_array);
    }
    
    function getSum()
    {
        return array_sum($this->_array);
    }
    
    function getCount()
    {
        return count($this->_array);
    }
    
    function reset()
    {
        reset($this->_array);
    }
    
    function getEach()
    {
        return each($this->_array);
    }
    
    function getFirst()
    {
        return reset($this->_array);
    }
    
    function getNext()
    {
        return next($this->_array);
    }
    
    function getPrev()
    {
        return prev($this->_array);
    }
    
    function getCurrent()
    {
        return current($this->_array);
    }
    
    function getLast()
    {
        return end($this->_array);
    }
    
    function getCurrentKey()
    {
        return key($this->_array);
    }
    
    /**
     * iviArray::getKeys()
     * 
     * Returns the keys from the array. If optional parameter $search is supplied only the keys
     * with the value of $search will be returned.
     * 
     * 
     * @param mixed $search - value of the keys to be returned (default is "").
     * @return array        - array with the matching keys
     */
    function getKeys($search = '')
    {
        if (empty($search)) {
            return array_keys($this->_array);
        }
        else {
            return array_keys($this->_array, $search);
        }
    }
    
    /**
     * iviArray::getRandom()
     * 
     * Returns a specified amount of random array elements
     * (see http://www.php.net/manual/de/function.array-rand.php)
     * 
     * @param int $amount - amount of elements to be returned (default is 1)
     * @return mixed      - key or array of keys of the array
     */
    function getRandom($amount = 1)
    {
        return array_rand($this->_array, $amount);
    }
    
    /**
     * iviArray::getSlice()
     * 
     * Returns a slice of the array starting at $start with the length of $length. 
     * If length is null, all elements beginning at $start will be returned.
     * (see http://www.php.net/manual/en/function.array-slice.php)
     * 
     * @param int $start  - starting offset
     * @param int $length - length of the slice
     * @return array      - array containing the desired values
     */
    function getSlice($start, $length = null)
    {
        if (is_null($length)) {
            return array_slice($this->_array, $start);
        }
        else {
            return array_slice($this->_array, $start, $length);
        }
    }
    
    /**
    * iviArray::contains()
    * 
    * Checks whether a given value exists in this array
    * 
    * @param mixed $value - value to be checked for existance
    * @param bool $strict - whether to check for data types or not (default is false)
    * @return bool        - whether the given value was found or not
    */
    function contains($value, $strict = false)
    {
        return in_array($value, $this->_array, $strict);
    }
    
    /**
    * iviArray::search()
    * 
    * Search the array for the given value
    * 
    * @param mixed $value - value to be searched for
    * @param bool $strict - whether to check for data types or not (default is false)
    * @return mixed       - key if it is found in the array, false otherwise
    */
    function search($value, $strict = false)
    {
        return array_search($value, $this->_array, $strict);
    }
    
    /**
    * iviArray::fetch()
    * 
    * Fetch data from a database result resource.
    * 
    * @param resource $resource - result resource
    * @param bool $assoc        - whether to apply field names of resource to array keys or not (compare http://www.php.net/manual/en/function.mysql-fetch-assoc.php) - default is true.
    * @param strinh $db         - database type. possible values: "mysql", "pgsql", "mssql", "msql"
    */
    function fetch(&$resource, $assoc = true, $db = 'mysql')
    {
        $array = array();
     
        if ($db == 'mysql') {
            if ($assoc) {
                while ($row = mysql_fetch_assoc($resource)) {
                    $array[] = $row;
                }
            }
            else {
                while ($row = mysql_fetch_row($resource)) {
                    $array[] = $row;
                }
            }
        }
        elseif ($db == 'pgsql') {
            if ($assoc) {
                while ($row = pg_fetch_assoc($resource)) {
                    $array[] = $row;
                }
            }
            else {
                while ($row = pg_fetch_row($resource)) {
                    $array[] = $row;
                }
            }
        }
        elseif ($db == 'mssql') {
            if ($assoc) {
                while ($row = mssql_fetch_assoc($resource)) {
                    $array[] = $row;
                }
            }
            else {
                while ($row = mssql_fetch_row($resource)) {
                    $array[] = $row;
                }
            }
        }
        elseif ($db == 'msql') {
            if ($assoc) {
                while ($row = msql_fetch_array($resource, MSQL_ASSOC)) {
                    $array[] = $row;
                }
            }
            else {
                while ($row = msql_fetch_row($resource)) {
                    $array[] = $row;
                }
            }
        }
     
        if (count($array) > 0) {
            $this->_array = $array;
        }
    }
    
    /**
    * iviArray::createComboBox()
    * 
    * Creates XHTML compliant code for a <select>-ComboBox using keys for the value attribute and values for the option titles
    * 
    * @param string $name     - value of the name attribute
    * @param string $selected - key name of the field to be selected (default is null = nothing selected)
    * @return string          - XHTML compliant code for the ComboBox
    */
    function createComboBox($name, $selected = null)
    {
        $result = '<select name="' . $name . '">' . "\n";
     
        foreach ($this->_array as $key => $val) {
            $result .= '  <option value="' . $key . '"';
       
            if ((!is_null($selected)) && ($selected == $key)) {
                $result .= ' selected="selected"';
            }
       
            $result .= '>' . $val . '</option>' . "\n";
        }
     
        $result .= '</select>';
     
        return $result;
    }
    
    /**
    * iviArray::apply()
    * 
    * Apply a callback function to each element of the array.
    * 
    * @param string $type     - type of user function. possible values:
    *                           "filter" - http://www.php.net/manual/en/function.array-filter.php
    *                           "reduce" - http://www.php.net/manual/en/function.array-reduce.php
    *                           "walk"   - http://www.php.net/manual/en/function.array-walk.php
    * 
    * @param string $function - name of the callback function
    * @param mixed  $param    - optional parameter(s) for the callback function
    * @return mixed           - returns bool or array depending on function type
    */
    function apply($type, $function, $param = null)
    {
        switch ($type) {
            case 'filter': return array_filter($this->_array, $function); break;
            case 'reduce': return (is_null($param)) ? (array_walk($this->_array, $function)) : (array_walk($this->_array, $function, $param)); break;
            case 'walk':   return (is_null($param)) ? (array_walk($this->_array, $function)) : (array_walk($this->_array, $function, $param)); break;
        }
    }
    
    /**
    * iviArray :: display()
    * 
    * Outputs array
    * 
    */
    function display($pre = false)
    {
        if ($pre) {
            print('<pre>');
        }
     
        print_r($this->_array);
     
        if ($pre) {
            print_r('</pre>');
        }
    }
}
 
?>
Return current item: iviArray