Skip to content

Instantly share code, notes, and snippets.

@mlconnor
Created June 25, 2012 17:19

Revisions

  1. mlconnor revised this gist Jun 25, 2012. 1 changed file with 3 additions and 2 deletions.
    5 changes: 3 additions & 2 deletions walk_array.php
    Original file line number Diff line number Diff line change
    @@ -14,8 +14,9 @@ function walk_recursive($obj, $closure) {
    return $newObj;
    } else if ( is_array($obj) ) {
    $newArray = array();
    foreach ($obj as $value) {
    $newArray[] = walk_recursive($value, $closure);
    foreach ($obj as $key => $value) {
    $key = $closure($key);
    $newArray[$key] = walk_recursive($value, $closure);
    }
    return $newArray;
    } else {
  2. mlconnor created this gist Jun 25, 2012.
    24 changes: 24 additions & 0 deletions walk_array.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    /**
    * works for json objects. will replace all
    * keys and values with the result of the
    * closure.
    */
    function walk_recursive($obj, $closure) {
    if ( is_object($obj) ) {
    $newObj = new stdClass();
    foreach ($obj as $property => $value) {
    $newProperty = $closure($property);
    $newValue = walk_recursive($value, $closure);
    $newObj->$newProperty = $newValue;
    }
    return $newObj;
    } else if ( is_array($obj) ) {
    $newArray = array();
    foreach ($obj as $value) {
    $newArray[] = walk_recursive($value, $closure);
    }
    return $newArray;
    } else {
    return $closure($obj);
    }
    }