Round a PHP 2d Array by a Specified Key
Round a specified key of a 2-dimentional PHP array. The first parameter is specified as a reference. This causes any changes, ie, the rounding function to effect the original array elements; array_walk_recursive() operates on all items in an array by a specified function.
array_walk_recursive($array, 'round2dArrayByKey');
function round2dArrayByKey(&$item) {
$n = 2; // set this to the rounding accuracy required
$item = round($item, $n);
}
Example:
PHP Array:
$array = array ( array(Classic Collections,"Abilene, TX 79602",2.71828,"red"), array(Fabulous Finds,"Abilene, TX 79601",3.14159,"blue"), array(Honeycomb Tree,"Abilene, TX 79601",1.41421,"green") );
PHP:
array_walk_recursive($array, 'round2dArrayByKey');
function round2dArrayByKey(&$item) { $item = round($item, 2); }
Produces this result:
Array ( [0] => Array ( [0] => Classic Collections [1] => Abilene, TX 79602 [2] => 2.72 [3] => https://www.facebook.com/Classic-Collections ) [1] => Array ( [0] => Fabulous Finds [1] => Abilene, TX 79601 [2] => 3.14 [3] => http://www.fabulousfinds.com/ ) [2] => Array ( [0] => Honeycomb Tree [1] => Abilene, TX 79601 [2] => 1.41 [3] => https://www.facebook.com/The-Honeycomb-Tree/ ) )