Skip to content

Instantly share code, notes, and snippets.

@postpostscript
Last active November 25, 2016 17:01
Show Gist options
  • Save postpostscript/63ee3faffb86613f379a to your computer and use it in GitHub Desktop.
Save postpostscript/63ee3faffb86613f379a to your computer and use it in GitHub Desktop.
PHP array manipulation
<?php
/**
* Author: Daniel Wilson <[email protected]> (https://github.com/danielrw7)
* Gist: https://gist.github.com/danielrw7/63ee3faffb86613f379a
*/
function props($key) {
$props = preg_split("/[\\.\\[\\]\\\"]/", trim($key));
$result = array();
foreach($props as $prop) {
if (strlen($prop)) {
$result[] = $prop;
}
}
return $result;
}
function assoc_get($result, $key = "") {
if (!$key) return $result;
$props = props($key);
foreach($props as $prop) {
$result = is_array($result) && isset($result[$prop]) ? $result[$prop] : null;
}
return $result;
}
function assoc_set($result, $key, $value = null) {
$tree = array(array($result));
$props = props($key);
foreach($props as $c => $prop) {
$last = $tree[count($tree)-1][0];
$set_value = ($c == count($props)-1);
if ($set_value) {
$tree[] = array(
$value,
$prop
);
} else {
if (isset($last[$prop]) && is_array($prop)) {
$tree[] = array(
$last[$prop],
$prop
);
} else {
$tree[] = array(
array(),
$prop
);
}
}
}
$value = $tree[count($tree)-1];
for($i = count($tree)-2; $i >= 0; $i--) {
$tree_item = $tree[$i];
$tree_child = $value;
$tree_item[0][$tree_child[1]] = $tree_child[0];
$value = $tree_item;
}
return $value[0];
}
<?php
assoc_get(array(
"key1" => 1,
"key2" => 2
), "key1");
// => 1
assoc_get(array(
"nested" => array(
"value" => 3
)
), "nested.value");
// => 3
assoc_set(array(
"x" => 1
), "x", 2);
// => array( "x" => 2 )
assoc_set(array(
"nested" => array(
"value" => 3
)
), "nested.value", 5);
// => array( "nested" => array( "value" => 5 ) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment