Skip to content

Instantly share code, notes, and snippets.

@ryasmi
Last active March 28, 2017 09:15
Show Gist options
  • Save ryasmi/a7a0757d7897d9b3e1de6d2bdf534faa to your computer and use it in GitHub Desktop.
Save ryasmi/a7a0757d7897d9b3e1de6d2bdf534faa to your computer and use it in GitHub Desktop.
<?php
function getIn($obj, $keys, $default = null) {
$key = $keys[0];
$rest = array_slice($keys, 1);
if ($obj instanceof StdClass) {
if (isset($obj->{$key})) {
if (count($rest) > 0) {
return getIn($obj->{$key}, $rest);
} else {
return $obj->{$key};
}
}
} else if (is_array($obj)) {
if (isset($obj[$key])) {
if (count($rest) > 0) {
return getIn($obj[$key], $rest);
} else {
return $obj[$key];
}
}
}
return $default;
}
$x = (object) ['a' => [10]];
echo json_encode(getIn($x, ['a', '0']));
<?php
function removeIn($obj, $keys, $default = null) {
$key = $keys[0];
$rest = array_slice($keys, 1);
if ($obj instanceof StdClass) {
if (isset($obj->{$key})) {
if (count($rest) > 0) {
$obj->{$key} = removeIn($obj->{$key}, $rest);
} else {
unset($obj->{$key});
}
}
} else if (is_array($obj)) {
if (isset($obj[$key])) {
if (count($rest) > 0) {
$obj[$key] = removeIn($obj[$key], $rest);
} else {
unset($obj[$key]);
}
}
}
return $obj;
}
$x = (object) ['a' => [10]];
echo json_encode(removeIn($x, ['a', 0]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment