Skip to content

Instantly share code, notes, and snippets.

@aaronpeterson
Last active August 29, 2015 13:57
Show Gist options
  • Select an option

  • Save aaronpeterson/9882497 to your computer and use it in GitHub Desktop.

Select an option

Save aaronpeterson/9882497 to your computer and use it in GitHub Desktop.

Revisions

  1. aaronpeterson revised this gist Mar 31, 2014. 1 changed file with 25 additions and 0 deletions.
    25 changes: 25 additions & 0 deletions DeepValueReaderSketch.php
    Original file line number Diff line number Diff line change
    @@ -46,3 +46,28 @@ public function getNameParts($name) {
    }

    function d($d) { ?><pre><?php var_dump($d); ?></pre><?php }

    /*
    So boss.
    string(13) "You found me!"
    string(13) "You found me!"
    NULL
    array(1) {
    ["foo"]=>
    array(1) {
    ["bar"]=>
    string(13) "You found me!"
    }
    }
    array(1) {
    ["bar"]=>
    string(13) "You found me!"
    }
    */
  2. aaronpeterson created this gist Mar 31, 2014.
    48 changes: 48 additions & 0 deletions DeepValueReaderSketch.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,48 @@
    <?php

    $data = array(
    'namespace' => array(
    'foo' => array(
    'bar' => 'You found me!'
    )
    )
    );

    $vs = new ValueStore;

    d( $vs->deepValue('namespace.foo.bar', $data) );
    d( $vs->deepValue('namespace[foo][bar]', $data) );
    d( $vs->deepValue('nope', $data) );
    d( $vs->deepValue('namespace', $data) );
    d( $vs->deepValue('namespace.foo', $data) );

    class ValueStore {
    public function deepValue($name, $data) {
    $data = (array) $data;

    $nameParts = $this->getNameParts($name);
    foreach ($nameParts as $part) {
    $data = empty($data[$part]) ? null : $data[$part];
    if (!$data)
    break;
    }

    return $data;
    }

    public function getNameParts($name) {
    if (strpos($name, '[') !== false) {
    // php style
    preg_match_all("/([^\[\]]+)/i", $name, $matches, PREG_PATTERN_ORDER);
    } elseif (strpos($name, '.') !== false) {
    // dot notation
    preg_match_all("/([^\.]+)/i", $name, $matches, PREG_PATTERN_ORDER);
    } else {
    $matches[] = array($name);
    }

    return $matches[0];
    }
    }

    function d($d) { ?><pre><?php var_dump($d); ?></pre><?php }