Created
July 7, 2017 14:41
-
-
Save ultrasamad/64a57b69c81f4e079c8022bfcf204863 to your computer and use it in GitHub Desktop.
This scripts collects all arguments of the function consisting of primitives and arrays and then flattens into a one dimensional array.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
*@author Ibrahim Samad | |
*@date 6/6/2017 | |
*@description A simple class that flatten a multi-dimensional array into a single array | |
*while taking care of null values. | |
*/ | |
class ArrayFlatter | |
{ | |
/* | |
*@param Array, primitives | |
*Receives any number of arguments: primitives and arrays | |
*and then do a recursive walk incase of an array to collect all the | |
*individuals array elements onto a parent array | |
* | |
*/ | |
public function flatten() | |
{ | |
$data = func_get_args()[0]; | |
return is_array($data) ? array_reduce($data, function($c, $a){ | |
return $this->format(array_merge($c, $this->flatten($a))); | |
}, []) : [$data]; | |
} | |
/* | |
*@param Array | |
*Convert null values to the string null. | |
*/ | |
private function format($array) | |
{ | |
return array_map(function($val){ | |
return $val != null ? $val : 'null'; | |
}, $array); | |
} | |
} | |
//Example usage | |
$obj = new ArrayFlatter; | |
echo '<pre>', print_r($obj->flatten(['a', ['b', 2], 3, null, [[4], ['c']]]), true),'</pre>'; | |
//produces | |
/*Array | |
( | |
[0] => a | |
[1] => b | |
[2] => 2 | |
[3] => 3 | |
[4] => null | |
[5] => 4 | |
[6] => c | |
)*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment