Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to take custom amount of data from foreach loop php laravel

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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.

>Solution :

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
}

Demo on 3v4l.org

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading