Skip to content

Instantly share code, notes, and snippets.

@morrelinko
Last active January 2, 2016 15:59
Show Gist options
  • Save morrelinko/8327101 to your computer and use it in GitHub Desktop.
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)
<?php
/**
* @author Morrison Laju <morrelinko@gmail.com>
*/
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;
}
}
@morrelinko
Copy link
Author

Simple usage here
http://pastebin.com/E0WEKnVs

@tmontana200000
Copy link

wow, it cool man love it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment