So in Eloquent there is a take()
and skip()
functions works like this:
$users = DB::table('users')->skip(10)->take(5)->get();
But now I'm reading data from a json file:
$path = storage_path() . "/app/public/userexam.json";
json_decode(file_get_contents($path), true);
So after reading data, I want to use a foreach
loop:
foreach($json as $js){
...
}
But I do need to take custom amount of records of $json
.
Something like this:
foreach($json->take(5) as $js){
...
}
But this thing obviously does not work and returns Call to a member function take() on array
.
So how can I use take and skip eloquent functions in a foreach loop in this case (or something equivalent to them).
I would really appreciate if you share any idea or suggestion about this...
Thanks.
CodePudding user response:
You can use array_slice
on the JSON array to implement skip
and take
. For example:
$skip = 10;
$take = 5;
foreach (array_slice($json, $skip, $take) as $js) {
// ... do what is necessary on the data
}
CodePudding user response:
You might need collect() method as the docs.
collect(json_decode(file_get_contents($path), true));
After that you might able to use take() or skip() method.