Last active
January 2, 2016 15:59
-
-
Save morrelinko/8327101 to your computer and use it in GitHub Desktop.
Takes an array of values from an array (with ability to rename keys and manipulate values)
This file contains 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 Morrison Laju <[email protected]> | |
*/ | |
class ArrayUtils | |
{ | |
/** | |
* Returns a new array created from another | |
* containing only the keys that we want. | |
* it also allows renaming a key from the original array. | |
* | |
* @param array $from The array we are taking data from | |
* @param array $keys The keys we want from the array | |
* @param bool $includeEmpty Should elements with empty values be allowed | |
* | |
* @return array | |
*/ | |
public static function take($from, $keys, $includeEmpty = true) | |
{ | |
if (self::isList($from)) { | |
return array_map(function ($item) use ($keys, $includeEmpty) { | |
return self::take($item, $keys, $includeEmpty); | |
}, $from); | |
} | |
$retrieved = array(); | |
array_walk($keys, | |
function (&$value, $index, $retrieved) use ($from, $includeEmpty) { | |
if (is_int($index) && !($value instanceof \Closure)) $index = $value; | |
if (array_key_exists($index, $from) && | |
($includeEmpty || ($includeEmpty == false && | |
!empty($from[$index]))) | |
) { | |
if ($value instanceof \Closure) { | |
$retrieved[0][$index] = call_user_func($value, $from[$index]); | |
} else { | |
$retrieved[0][$value] = $from[$index]; | |
} | |
} | |
}, array(&$retrieved)); | |
return $retrieved; | |
} | |
} |
wow, it cool man love it
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple usage here
http://pastebin.com/E0WEKnVs