/** * Get an item from an array using "dot" notation. * * @param array $array array we're working on * @param string $key key we want to get in the array, in the following format "key1.key2.key3" * * @return mixed obtained value */ function array_dot_get($array = null, $key = null) { if (is_null($key)) { return $array; } if (isset($array[$key])) { return $array[$key]; } $explodedKey = explode('.', $key); $sk = count($explodedKey); $return = []; foreach ($array as $node => $value) { if (\Anekdotes\Support\Str::startsWith($node, $key)) { $explodedNodeName = explode('.', $node); $sn = count($explodedNodeName); if ($sn > $sk + 1) { $newNodeName = $explodedNodeName[$sk]; $return[$newNodeName] = array_dot_get($array, $key . '.' . $newNodeName); } else { $return[$explodedNodeName[$sn - 1]] = $value; } } } return $return; }
function array_dot_get($array, $key) { if (is_null($key)) { return $array; } if (isset($array[$key])) { return $array[$key]; } $explodedKey = explode('.', $key); $sk = sizeof($explodedKey); $return = array(); foreach ($array as $node => $value) { if (strpos($node, $key) === 0) { $explodedNodeName = explode('.', $node); $sn = sizeof($explodedNodeName); if ($sn > $sk + 1) { $newNodeName = $explodedNodeName[$sk]; $return[$newNodeName] = array_dot_get($array, $key . '.' . $newNodeName); } else { $return[$explodedNodeName[$sn - 1]] = $value; } } } return $return; }
public function testArrayDotGet7() { $array = ['toaster.cod.sam.juggernaut' => 'op', 'mathieu' => 'patate']; $final = ['sam' => ['juggernaut' => 'op']]; $this->assertEquals(array_dot_get($array, 'toaster.cod'), $final); }
/** * Returns a value or more in the items, using the dot notation to decide where to fetch from. * * Ex: * $this->items = ["toaster.Sam" => "CoD","toaster.test" => "Toast","Mathieu" => "Patate"]; * $this->group('toaster'); will then give ["Sam" => "CoD","test" => "Toast] * * @param string $key A string representing all the keys needed, seperated by a dot * * @return array An array of all the values asked by the key string */ public function group($key) { return array_dot_get($this->all(), $key); }
public static function group($key) { return array_dot_get(self::$items, $key); }
public function testArrayDotGet() { $data = array('one.two.three.dak' => '#333', 'one.two.three.derp' => 'My name is what?', 'one' => 1); $expectedResult = array('three' => array('dak' => '#333', 'derp' => 'My name is what?')); $this->assertEquals($expectedResult, array_dot_get($data, 'one.two')); }