Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

php - abs of an array

Which is the easy way of getting the abs of an array in php? It has to be a better way. This works, but in multidimensional array it has some limitations

function make_abs($numbers) {
 $abs_array = array();

 foreach($numbers as $key=>$value)
   $abs_array[$key] = abs($value);

 return $abs_array;
}
question from:https://stackoverflow.com/questions/65928064/absolute-value-implode

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your variant using references (this does not solve your recursion problem, just FYI):

function make_abs(&$numbers)
{
    foreach($numbers as &$value)
        $value = abs($value)
    ;
}

For the recursion problem, you need to step into each array:

function make_abs(&$numbers)
{
    foreach($numbers as &$value)
        is_array($value) ? make_abs($value) : $value = abs($value)
    ;
}

PHP itself has a somewhat handy function for that, array_walk_recursiveDocs. The problem with that function is, it expects the callback to have two parameters, value (by reference) and key. Many PHP functions do not fit those requirements. You can work around that by creating yourself a helper function to use any function that only takes one parameter and returns the modified value. You pass the function as with array_mapDocs:

function array_walk_recursive_map(array &$array, $callback)
{
    $byRef = function(&$item, $key) use ($callback)
    {
        $item = $callback($item);
    };
    array_walk_recursive($array, $byRef);
}

# Usage:
array_walk_recursive_map($numbers, 'abs');

Hope this is helpful.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...