Last active
March 28, 2017 09:15
-
-
Save ryasmi/a7a0757d7897d9b3e1de6d2bdf534faa to your computer and use it in GitHub Desktop.
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 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'])); |
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 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