質問

Hey guys I have some seriously hacky code going on with a nested function, but I cannot get it to work for some reason with either closures or lambda functions, which I would assume would be preferable, would someone help me understand how I can turn this into either a closure, lambda or something else as to NOT pollute my Global scope with unneeded B.S. ??

Here's my two methods

/**
 * Sort an array of object is ASC order.
 * @param   object  $objArray   An array of objects
 * @return  object  Sorted array of objects
 */
protected function objSort($objArray) 
{
    // turns an Object Array into and Assoc Array
    $array = self::objToArr($objArray);

    // avoid recursively declaring the function
    if (! function_exists('dsort')) 
    {
        // nested functions are stupid.
        function dsort(&$array) 
        {
            foreach ($array AS &$current) 
            {
                if (is_array($current)) dsort($current);
            }
            ksort($array);
        }
    }

    dsort($array);

    // back to an Object Array
    return $objArray = json_decode(json_encode($array));
}

/**
 * Turns an object array into an associative multidimensional array.
 * @param   object  $object     An array of objects
 * @return  array   An associative array    
 */
private static function objToArr($object) 
{
    $array = array();
    $arrayObject = is_object($object) ? get_object_vars($object) : $object;
    foreach ($arrayObject as $key => $value) 
    {
        $value       = (is_array($value) || is_object($value)) ? self::objToArr($value) : $value;
        $array[$key] = $value;
    }
    return $array;
}

They will take an array of objects, sort them alphabetically as an associative array, and return them as an array of objects.

役に立ちましたか?

解決

I'm not super cleaar on what you are trying to do here (sort an objects properties by name within each object). When you talk about polluting the global space I'm assuming you are referring to the implementation of dsort, this can be contained in the class using this method:

protected static function dsort(&$array) 
{
    foreach ($array AS &$current) 
    {
        if (is_array($current)) dsort($current);
    }
    ksort($array);
}

then invoked when needed (after replacing classname with the classes' name) by

$dsort = array("classname", "dsort");
$dsort($array);

or if you prefer

call_user_func(array("classname","dsort"), $array);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top