Skip to content

Commit d4a37b6

Browse files
committed
Data preparation code updated
1 parent 85fd225 commit d4a37b6

File tree

3 files changed

+26
-26
lines changed

3 files changed

+26
-26
lines changed

example/index.php

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,5 +36,4 @@
3636
$data = $json->collect([1, 2, 3, 4, 5])->nth(-2);
3737

3838
echo '<pre>';
39-
dump($data);
40-
*/
39+
dump($data);

src/JsonQueriable.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,27 @@ public function isJson($value, $return_map = false)
161161

162162
return (json_last_error() == JSON_ERROR_NONE) ? ($return_map ? $data : true) : json_last_error_msg();
163163
}
164+
protected function prepareResult($data, $object)
165+
{
166+
$output = [];
167+
if (is_array($data)) {
168+
foreach ($data as $key => $val) {
169+
if ($object) {
170+
$output[$key] = (object) $val;
171+
} else {
172+
$output[$key] = $val;
173+
}
174+
}
175+
} else {
176+
if ($object) {
177+
$output = json_decode(json_encode($data));
178+
} else {
179+
$output = json_decode(json_encode($data), true);
180+
}
181+
}
182+
183+
return $output;
184+
}
164185

165186
/**
166187
* read JSON data from file

src/Jsonq.php

Lines changed: 4 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -91,16 +91,8 @@ public function get($object = true)
9191
if (!$this->isMultiArray($this->_map)) {
9292
return (object) $this->_map;
9393
}
94-
$resultingData = [];
95-
foreach ($this->_map as $key=>$data) {
96-
if ($object) {
97-
$resultingData[$key] = (object) $data;
98-
} else {
99-
$resultingData[$key] = $data;
100-
}
101-
}
10294

103-
return $resultingData;
95+
return $this->prepareResult($this->_map, $object);
10496
}
10597

10698

@@ -286,11 +278,7 @@ public function first($object = true)
286278

287279
$data = $this->_map;
288280
if (count($data) > 0) {
289-
if ($object) {
290-
return json_decode(json_encode(reset($data)));
291-
}
292-
293-
return json_decode(json_encode(reset($data)), true);
281+
return $this->prepareResult(reset($data), $object);
294282
}
295283

296284
return null;
@@ -309,11 +297,7 @@ public function last($object = true)
309297

310298
$data = $this->_map;
311299
if (count($data) > 0) {
312-
if ($object) {
313-
return json_decode(json_encode(end($data)));
314-
}
315-
316-
return json_decode(json_encode(end($data)), true);
300+
return $this->prepareResult(end($data), $object);
317301
}
318302

319303
return null;
@@ -345,11 +329,7 @@ public function nth($index, $object = true)
345329
$result = $data[$this->count() + $index];
346330
}
347331

348-
if ($object) {
349-
return json_decode(json_encode($result));
350-
}
351-
352-
return json_decode(json_encode($result), true);
332+
return $this->prepareResult($result, $object);
353333
}
354334

355335
/**

0 commit comments

Comments
 (0)