Skip to content

Instantly share code, notes, and snippets.

@luishgp
Last active October 8, 2021 14:56
Show Gist options
  • Save luishgp/ed030b70322b68331b19e431009ba240 to your computer and use it in GitHub Desktop.
Save luishgp/ed030b70322b68331b19e431009ba240 to your computer and use it in GitHub Desktop.
Método DataGet
<?php
if (!function_exists('value')) {
/**
* Return the default value of the given value.
*
* @param mixed $value
* @return mixed
*/
function value($value)
{
return $value instanceof Closure ? $value() : $value;
}
}
if (! function_exists('array_accessible')) {
/**
* Determine whether the given value is array accessible.
*
* @param mixed $value
*
* @return bool
*/
function array_accessible($value)
{
return is_array($value) || $value instanceof ArrayAccess;
}
}
if (! function_exists('array_exists')) {
/**
* Determine if the given key exists in the provided array.
*
* @param \ArrayAccess|array $array
* @param string|int $key
*
* @return bool
*/
function array_exists($array, $key)
{
if ($array instanceof ArrayAccess) {
return $array->offsetExists($key);
}
return array_key_exists($key, $array);
}
}
if (! function_exists('data_get')) {
/**
* Get an item from an array or object using "dot" notation.
*
* @param mixed $target
* @param string|array|int|null $key
* @param mixed $default
* @return mixed
*/
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 (! is_array($target)) {
return value($default);
}
$result = array();
foreach ($target as $item) {
$result[] = data_get($item, $key);
}
return in_array('*', $key) ? array_collapse($result) : $result;
}
if (array_accessible($target) && array_exists($target, $segment)) {
$target = $target[$segment];
} elseif (is_object($target) && isset($target->{$segment})) {
$target = $target->{$segment};
} else {
return value($default);
}
}
return $target;
}
}
$arrayTeste = array(
"propA" => array(
"propB" => (object) array(
"propC" => array(
"hello" => "Hello World Array",
),
),
),
);
$arrayTeste2 = array(
"propA" => array(
"propB" => (object) array(
"propC" => null,
),
),
);
$objetoTeste = (object) array(
"propA" => array(
"propB" => array(
"propC" => (object) array(
"hello" => "Hello World Objeto",
),
),
),
);
$objetoTeste2 = (object) array(
"propA" => array(
"propB" => array(
"propC" => (object) array(),
),
),
);
echo data_get($arrayTeste, 'propA.propB.propC.hello', 'Não achou no $arrayTeste');
echo ' ';
echo data_get($objetoTeste, 'propA.propB.propC.hello', 'Não achou no $objetoTeste');
echo ' ';
echo data_get($arrayTeste2, 'propA.propB.propC.hello', 'Não achou no $arrayTeste2');
echo ' ';
echo data_get($objetoTeste2, 'propA.propB.propC.hello', 'Não achou no $objetoTeste2');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment