Last active
December 15, 2020 20:48
-
-
Save dib258/f927f699bf12095c67b6a6317e2eef27 to your computer and use it in GitHub Desktop.
Laravel Helper
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 | |
function data_get($target, $key, $default = null) | |
{ | |
if (is_null($key)) { | |
return $target; | |
} | |
$key = is_array($key) ? $key : explode('.', $key); | |
foreach ($key as $i => $segment) { | |
unset($key[$i]); | |
if (is_null($segment)) { | |
return $target; | |
} | |
if ($segment === '*') { | |
if ($target instanceof Collection) { | |
$target = $target->all(); | |
} elseif (! is_array($target)) { | |
return value($default); | |
} | |
$result = []; | |
foreach ($target as $item) { | |
$result[] = data_get($item, $key); | |
} | |
return in_array('*', $key) ? Arr::collapse($result) : $result; | |
} | |
if (Arr::accessible($target) && Arr::exists($target, $segment)) { | |
$target = $target[$segment]; | |
} elseif (is_object($target) && isset($target->{$segment})) { | |
$target = $target->{$segment}; | |
} else { | |
return value($default); | |
} | |
} | |
return $target; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment