简体   繁体   中英

Need a more elegant way to test and loop through array

I'm looping through about 40,000 records and printing vehicle information when matches are found. A record will have at least one vehicle, which consists of 7 elements. It may have up to 16 total vehicles, though. Any one of the 16 vehicles may have an incomplete or blank vehicle identification number (that's the last element), in which case I don't want to use it. So I test element 6, 13, 20, 27 first to make sure something is there, and then that it isn't just whitespace.

I'm new to PHP, as my code will show. What I have below works, although it's long, cumbersome, and seems to take a lot longer than it should.

An array might look like this:

[0] => VEHICLE1
[1] => 1995
[2] => FORD
[3] => XL
[4] => WHITE
[5] => MD
[6] => 1GNEK714XXXXXXX
[7] => VEHICLE2
[8] => 1999
[9] => FORD
[10] => F-150XLT (HAS THIRD DOOR ON PASSENGER SIDE)
[11] => TEAL (GREEN)
[12] => MD
[13] => 

My logic is this:

-Test the last element to make sure there is a vehicle ID number, if yes..
-Make sure the vehicle ID is greater than 0. If yes..
-Left justify the VIN and pad to 20 characters,
-Print the vehicle info (Year, Make, Model, Color)

// VEHICLE 1
if(isset($vehicle_info[1][6]) && strlen($vehicle_info[1][6])>0){
print str_pad($vehicle_info[1][6], 20).$vehicle_info[1][5]."#8";
print "$details {$vehicle_info[1][1]}     
{$vehicle_info[1][2]} {$vehicle_info[1][3]} {$vehicle_info[1][4]}  \r\n";}

// VEHICLE 2
if(isset($vehicle_info[1][13]) && strlen($vehicle_info[1][13])>0){
print str_pad($vehicle_info[1][13], 20).$vehicle_info[1][12]."#8";
print "$details {$vehicle_info[1][8]}}
{$vehicle_info[1][9]} {$vehicle_info[1][10]} {$vehicle_info[1][11]}\r\n"}

...and so on, 14 more times...

Any help in tightening/speeding this up would be appreciated. I'm sure there's a way to do this in 3 lines, I just haven't figured it out yet!

if info about every vehicle takes 7 items of array, use array_chunk and work with parts

$vehicles = array_chunk($vehicle_info[1], 7);

foreach ($vehicles as $vehicle) {
   if(isset($vehicle[6]) && strlen($vehicle[6])>0){
   print str_pad($vehicle[6], 20).$vehicle[5]."#8";
   print "$details {$vehicle[1]}     
   {$vehicle[2]} {$vehicle[3]} {$vehicle[4]}  \r\n";}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM