Skip to content

Commit 8580ba8

Browse files
authored
Merge pull request #4 from me-shaon/master
'nth' method refactored for better performance
2 parents 5a3fe78 + cc5d6d9 commit 8580ba8

File tree

2 files changed

+13
-14
lines changed

2 files changed

+13
-14
lines changed

example/index.php

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,13 @@
2828
$avg = $json->collect([1, 3, 2])->avg();
2929
3030
echo '<pre>';
31-
dump($avg);*/
31+
dump($avg);*/
32+
33+
34+
/* ----------- nth method example ---------- */
35+
/*$json=new Jsonq($rootDir . 'data.json');
36+
$data = $json->collect([1, 2, 3, 4, 5])->nth(-2);
37+
38+
echo '<pre>';
39+
dump($data);
40+
*/

src/Jsonq.php

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -330,25 +330,15 @@ public function nth($index, $object = true)
330330
$data = $this->_map;
331331
$total_elm = count($data);
332332
$idx = abs($index);
333-
$result = [];
334333

335-
336-
if (!is_integer($index) || $total_elm < $idx || $index == 0) {
334+
if (!is_integer($index) || $total_elm < $idx || $index == 0 || !is_array($this->_map)) {
337335
return null;
338336
}
339337

340338
if ($index > 0) {
341-
$result = current($data);
342-
343-
for ($i = 1; $i<$index; $i++) {
344-
$result = next($data);
345-
}
339+
$result = $data[$index - 1];
346340
} else {
347-
$result = end($data);
348-
349-
for ($i = 1; $i < $idx; $i++) {
350-
$result = prev($data);
351-
}
341+
$result = $data[$this->count() + $index];
352342
}
353343

354344
if ($object) {

0 commit comments

Comments
 (0)