I have a JSON array like this:
[
{"location":"1","distance":"25.75206"},
{"location":"2","distance":"21.49343"},
{"location":"3","distance":"24.13432"}
]
Right now I am doing a foreach
with every $location
to get the corresponding data.
$locations = json_decode($locations, true);
foreach ($locations as $key => $value) {
if ($value['location'] == $location) {
$distance = $value['distance'];
}
}
The problem is, the arrays can be very big with several thousand items, so doing a foreach
is quite resource intensive and can slow things down.
Is there any more "direct" and less resource intensive way of getting each corresponding value?
foreach is quite resourced intensive and can slow things down because it copies input array and works with this copy. If you want to avoid this behavior you can use access by a pointer. For example, you can use reset
, next
and current
construction for working with a pointer
$value = reset($locations);
while ($element !== false) {
if ($value['location'] == $location) {
$distance = $value['distance'];
}
next($locations);
$value = current($locations);
}
And of course, you can use a pointer in foreach
. For example:
foreach ($locations as $key => &$value) {
if ($value['location'] == $location) {
$distance = $value['distance'];
}
}
I am not a PHP guy, I don't know if this applies here, but in general (not necessarily in all cases) if you have a list of something and know the size or can detect the end you can iterate through it and access each item with the index number (ie, list[0], list[1], list[2], etc). Iterating through a list in this way is typically faster, but again I don't know PHP and perhaps that isn't true in this situation.
I'll also add, while I don't know the environment in which you are implementing this, in many cases it isn't really going to matter. foreach
implementations in many languages are often very optimized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With