Example #1
0
/**
 * @collections @get
 *
 ** __::get(['foo' => ['bar' => 'ter']], 'foo.bar');
 ** // → 'ter'
 */
function get($collection = array(), $key = '', $default = null)
{
    if (\objects\isNull($key)) {
        return $collection;
    }
    if (!\objects\isObject($collection) && isset($collection[$key])) {
        return $collection[$key];
    }
    foreach (\explode('.', $key) as $segment) {
        if (\objects\isObject($collection)) {
            if (!isset($collection->{$segment})) {
                return $default instanceof \Closure ? $default() : $default;
            } else {
                $collection = $collection->{$segment};
            }
        } else {
            if (!isset($collection[$segment])) {
                return $default instanceof \Closure ? $default() : $default;
            } else {
                $collection = $collection[$segment];
            }
        }
    }
    return $collection;
}
Example #2
0
/**
 * Returns an array of values belonging to a given property of each item in a collection.
 *
 * @param array  $collection rray
 * @param string $property property
 *
 * @return array|object
 *
 */
function pluck($collection = [], $property = '')
{
    $plucked = \array_map(function ($value) use($property) {
        return \collections\get($value, $property);
    }, (array) $collection);
    if (\objects\isObject($collection)) {
        $plucked = (object) $plucked;
    }
    return $plucked;
}