dongwuzun4630 2015-07-13 19:28
浏览 7

需要一种更优雅的方式来测试和循环遍历数组

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]}  
";}

// 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]}
"}

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

  • 写回答

1条回答 默认 最新

  • dpstir0081 2015-07-13 19:42
    关注

    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]}  
    ";}
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类