2014-03-27 48 views
0

從每個陣列拉出數據1解析一些數據後我有這樣的實例陣列:通過多維數組循環並在一個時間

array (
    0 => 
    array (
    0 => '3 1/2 cups peeled and diced potatoes', 
    1 => '1/3 cup diced celery', 
    2 => '1/3 cup finely chopped onion', 
    3 => '2 tablespoons chicken bouillon granules', 
    4 => '3 1/2 cups peeled and diced potatoes', 
    5 => '1/3 cup diced celery', 
    6 => '1/3 cup finely chopped onion', 
    7 => '2 tablespoons chicken bouillon granules', 
), 
    1 => 
    array (
    0 => '3 1/2', 
    1 => '1/3', 
    2 => '1/3', 
    3 => '2', 
    4 => '3 1/2', 
    5 => '1/3', 
    6 => '1/3', 
    7 => '2', 
), 
    2 => 
    array (
    0 => 'cup', 
    1 => 'cup', 
    2 => 'cup', 
    3 => 'tablespoon', 
    4 => 'cup', 
    5 => 'cup', 
    6 => 'cup', 
    7 => 'tablespoon', 
), 
    3 => 
    array (
    0 => 'peeled and diced potatoes', 
    1 => 'diced celery', 
    2 => 'finely chopped onion', 
    3 => 'chicken bouillon granules', 
    4 => 'peeled and diced potatoes', 
    5 => 'diced celery', 
    6 => 'finely chopped onion', 
    7 => 'chicken bouillon granules', 
), 
) 

不需要第一陣列了。數組1 - 3我需要遍歷並將結果存儲在mySQL中,但它們需要與ala數組0相關聯。所以:

array1 0,array2 0,array3 0全部屬於一起 array1 1,數組2 1,ARRAY3 1都屬於一起 等

這裏是我完成這個代碼:

//make sure there were matches found and if there were, organize the array 
if(!empty($matches)) { 
    $info_array = array(); 
    for ($i = 0; $i < count($matches); $i++) { 
     for ($j = 1; $j < count($matches[$i]); $j++) { 
      if ($j == 1) { 
       $key = 'amount'; 
      } 
      elseif ($j == 2) { 
       $key = 'size'; 
      } 
      elseif ($j == 3) { 
       $key = 'ingredient'; 
      } 
      $info_array[$i][$key] = $matches[$j][$i]; 
     } 
    } 

不幸的是,這是行不通的。它產生這樣的輸出:

array (
    0 => 
    array (
    'amount' => '3 1/2', 
    'size' => 'cup', 
    'ingredient' => NULL, 
), 
    1 => 
    array (
    'amount' => '1/3', 
    'size' => 'cup', 
    'ingredient' => NULL, 
), 
    2 => 
    array (
    'amount' => '1/3', 
    'size' => 'cup', 
    'ingredient' => NULL, 
), 
    3 => 
    array (
    'amount' => '2', 
    'size' => 'tablespoon', 
    'ingredient' => NULL, 
), 
) 

這只是製備4-陣列和我需要8.計數($匹配)是= 8,所以它的運行第一回路8倍。我不確定我要去哪裏錯。有任何想法嗎?非常感謝幫助!

回答

2

通過下面的代碼

if(!empty($matches)) { 
    $info_array = array(); 
    $total = count($matches[0]); 
    for ($i = 0; $i < $total; $i++) { 
     for ($j = 1; $j < count($matches); $j++) { 
      if ($j == 1) { 
       $key = 'amount'; 
      } 
      elseif ($j == 2) { 
       $key = 'size'; 
      } 
      elseif ($j == 3) { 
       $key = 'ingredient'; 
      } 
      $info_array[$i][$key] = $matches[$j][$i]; 
     } 
    } 
} 
取代你的循環代碼