diff --git a/src/Peekmo/JsonPath/JsonStore.php b/src/Peekmo/JsonPath/JsonStore.php index 2c5b4f4..99a7fd7 100644 --- a/src/Peekmo/JsonPath/JsonStore.php +++ b/src/Peekmo/JsonPath/JsonStore.php @@ -81,9 +81,10 @@ public function toArray() * Gets elements matching the given JsonPath expression * @param string $expr JsonPath expression * @param bool $unique Gets unique results or not + * @param bool $keyFromPath ability to retain pathing in key separated by a | * @return array */ - public function get($expr, $unique = false) + public function get($expr, $unique = false, $keyFromPath = false) { if ((($exprs = $this->normalizedFirst($expr)) !== false) && (is_array($exprs) || $exprs instanceof \Traversable) @@ -97,11 +98,23 @@ public function get($expr, $unique = false) preg_replace(array("/^\\$\[[\"']?/", "/[\"']?\]$/"), "", $expr) ); + $path = ""; for ($i = 0; $i < count($keys); $i++) { + + $path .= $keys[$i]; + if ($i < count($keys) - 1) { + $path .= '|'; + } + $o =& $o[$keys[$i]]; } - $values[] = & $o; + if ($keyFromPath) { + $values[$path] = & $o; + } + else { + $values[] = & $o; + } } if (true === $unique) { diff --git a/tests/JsonStoreTest.php b/tests/JsonStoreTest.php index ec3a80c..73aa09f 100644 --- a/tests/JsonStoreTest.php +++ b/tests/JsonStoreTest.php @@ -93,6 +93,23 @@ public function testGetAllByKeyFiltered() $expected = ["fiction", "fiction"]; $this->assertEquals($data, $expected); } + + public function testGetMaintainPath() + { + $jsonStore = new JsonStore('{"body":[{"name":"Peter Peterson","age":22,"gender":"Male"},{"name":"John Johnston","age":64}]}'); + $data = $jsonStore->get("$.body[*]", false, true); + $expected = array( 'body|0' => array( + 'name' => 'Peter Peterson', + 'age' => 22, + 'gender' => 'Male' + ), + 'body|1' => array ( + 'name' => 'John Johnston', + 'age' => 64 + )); + + $this->assertEquals($data, $expected); + } public function tearDown() {