I am trying to figure out how to loop through the first one so that it loops through the second one as long as the key (Rack_Id) are the same, is the correct way to do this like…
foreach($racks2 as $key => $value) {
...
foreach($racks[$key] as $value) {
...
}
}
A) Your example doesn’t contain enough information to help you. You would need to show enough example data and the result you expect from that data so that someone would know what you mean by ‘it loops through the second one as long as the key (Rack_Id) are the same’. Show at least two pieces of data in the first array and show both matching and non-matching data in the second array. The way I read the example is that you want to get the matching ‘title’, and perhaps other values, out of $racks, for the current rack_id.
B) In your proposed code, the $key value is the numerical [0] index, having nothing to do with the rack_id values. If doing this in php was the best way (see the next point in this list), indexing/pivoting the data, using the rack_id values, rather than the zero referenced numerical index, when you fetch it, would allow you to directly access any related data, rather than to loop over all data to try and find it.
C) Since this is related/relational data values, the ‘R’ in RDBMS, just do all of this in one query, then produce the output you want from the data that the query matches.
ok, I have 2 arrays.
One holds all the racks (title, rack_id)
The 2nd array hold devices which have a rack_id)
So im trying to get all the devices which would have a rack_id.
So would something like this be better?
foreach($racks['Rack_Id'] as $rack) {
//rack detail
foreach($devices as $device) {
//device associated with rack
}
}
And I couldnt see a connection on the file uploading link…
But since I wanted to list all the devices of a certain Rack_Id along with the title of the rack.
So I thought it would be best to have 1 array to hold all the racks and another to hold the devices, then just loop though the racks and looping through the devices for every rack. Is that not the way to do it
Then when rendering to the page you can use DB fields related to the RACK in the outside loop using the ‘Rack’ KEY and Device fields in the inner loop with the ‘Devices’ KEY.
foreach($devices as $Rack_Id => $ar):
if(!empty($Rack_Id)):
//in this loop echo anything Rack Related under the key Rack.
echo $devices[$Rack_Id]['Rack']['Rack_Id'].'<br>';
echo $devices[$Rack_Id]['Rack']['Rack_Title'].'<br>';
//Then loop through all devices on the rack and use the fields related to devices
foreach($devices[$Rack_Id]['Devices'] as $Device_Id => $arr):
if(!empty($Device_Id)):
echo $devices[$Rack_Id]['Devices'][$Device_Id]['Device_Id'].'<br>';
echo $devices[$Rack_Id]['Devices'][$Device_Id]['Device'].'<br>';
endif;
endforeach;
endif;
endforeach;
Anyway, something like this should work. Untested.