JBZoo\Data\Data::find PHP Method

find() public method

Example: $data->find('parentkey.subkey.subsubkey');
public find ( string $key, mixed $default = null, mixed $filter = null, string $separator = '.' ) : mixed
$key string The key to search for. Can be composed using $separator as the key/subkey separator
$default mixed The default value
$filter mixed Filter returned value
$separator string The separator to use when searching for subkeys. Default is '.'
return mixed
    public function find($key, $default = null, $filter = null, $separator = '.')
    {
        $value = $this->get($key);
        // check if key exists in array
        if (null !== $value) {
            return $this->_filter($value, $filter);
        }
        // explode search key and init search data
        $parts = explode($separator, $key);
        $data = $this;
        foreach ($parts as $part) {
            // handle ArrayObject and Array
            if (($data instanceof \ArrayObject || is_array($data)) && isset($data[$part])) {
                $data = $data[$part];
                continue;
            }
            // handle object
            if (is_object($data) && isset($data->{$part})) {
                $data =& $data->{$part};
                continue;
            }
            return $this->_filter($default, $filter);
        }
        // return existing value
        return $this->_filter($data, $filter);
    }

Usage Example

コード例 #1
0
ファイル: FilterTest.php プロジェクト: jbzoo/data
 public function testFilter()
 {
     $value = '  123.456 string <i>qwerty</i>  ';
     $data = new Data(array('key' => $value, 'array' => array('inner' => $value)));
     // Default value
     isSame(null, $data->get('undefined'));
     isSame(42.123, $data->get('undefined', 42.123));
     isSame(42, $data->get('undefined', 42.123, 'int'));
     isSame(42.123, $data->get('undefined', '42.123', 'float'));
     // Get & find
     isSame($value, $data->get('key'));
     isSame($value, $data->find('key'));
     isSame($value, $data->find('array.inner'));
     // One filter
     isSame(123, $data->get('key', null, 'int'));
     isSame(123, $data->find('key', null, 'int'));
     isSame(123, $data->find('array.inner', null, 'int'));
     // Several filters
     isSame('stringqwerty', $data->get('key', null, 'strip, trim, alpha'));
     isSame('stringqwerty', $data->find('key', null, 'strip, trim, alpha'));
     isSame('stringqwerty', $data->find('array.inner', null, 'strip, trim, alpha'));
     // Several filters
     isSame('123.456 string qwerty', $data->get('key', null, function ($value) {
         return trim(strip_tags($value));
     }));
     isSame('123.456 string qwerty', $data->find('key', null, function ($value) {
         return trim(strip_tags($value));
     }));
     isSame('123.456 string qwerty', $data->find('array.inner', null, function ($value) {
         return trim(strip_tags($value));
     }));
 }
All Usage Examples Of JBZoo\Data\Data::find