I have a two-dimensional array and I need to add key-value pairs to the ‘inner’ arrays conditionally, and then write the updated arrays back to the outer array. All the ‘inner’ arrays have the same structure. In the snippet below the first or outer ‘foreach’ is looping around calculating $dist values. It’s the inner ‘foreach’ loop that concerns me here.
I am trying to add the key-value pairs ‘dist=$dist’ and ‘unit’=‘miles’ to each $listing. They get added to $listing, but this altered $listing wasn’t getting written back to $listings (plural). So I’ve resorted to writing the altered $listing into a new outer array, and then changing its name back to $listings afterwards. Surely there’s a better way ?
// Calculate all the distances and add to $listing array
foreach ($bus_ids as $bus_id) {
if (array_key_exists($bus_id, $latlongs)) {
$lat = $latlongs[$bus_id]['lat'];
$lng = $latlongs[$bus_id]['lng'];
$dist = distance($lat, $lng, $lat2, $lng2, true);
// echo $bus_id . " Distance: " . $dist;
foreach ($listings as $listing) {
if ($bus_id == $listing['bus_id']) {
$listing['dist'] = $dist;
$listing['unit'] = 'miles';
$newlistings[] = $listing;
break; // bus_id is unique
}
}
}
}
$listings = $newlistings;
I have tried:
foreach ($listings as $key => $listing) {
. . .
$listings[$key] = $listing;
. . .
and also:
foreach ($listings as &$listing) {
Neither seem to work, but perhaps I’ve not got it quite right.
Curiously when it comes to altering the values in those same key-value pairs the assignment operator seems to work OK. This code follows almost immediately after the snippet above.
// $listings gets sorted by the value of $listing['dist']
// Convert small distances to yards
foreach ($listings as &$listing) {
if (isset($listing['dist']) && $listing['dist'] < 0.5) {
$listing['dist'] = round($listing['dist']*1760,-1);
$listing['unit'] = 'yards';
}
// $newlistings[] = $listing; (not needed here)
}
// $listings = $newlistings; (not needed here)
It appears that I can’t ADD to an array using the assignment operator or ‘as $key => $value’ construction, but it is OK for altering something that already exists. Or have I just got my syntax muddled ?