2013-03-15 316 views
-1

我的問題是如何將數組值粘貼到變量中,當我循環訪問它們時。循環訪問數組

我正在使用它來獲取我的數組 - 我需要查詢中的兩個值。

$categ = array(); 
while ($row = mysql_fetch_array($result)) { 
    array_push($categ, array(
     'cat' => $row["CategoryName"], 
     'course' => $row["Course"] 
    )); 
} 

這裏有重複,所以我使用以下方法來獲得一系列獨特:

$categ = array_map("unserialize", array_unique(array_map("serialize", $categ))); 

這給出了以下的輸出:

Array (
    [0] => Array ([cat] => Dogs [course] => Kempton Park) 
    [2] => Array ([cat] => Dogs [course] => Lingfield Park) 
    [4] => Array ([cat] => Gallops [course] => Wincanton) 
) 

我當時想遍歷這個數組將[cat]和[course]的值分配給兩個變量:$cat$course

我嘗試了各種方法,但它不工作:下面給出了一個語法錯誤 - 不知道爲什麼?

foreach ($categ as list($cat2, $course2)){ 
    require ('C04_by_Account_by_Bet.php'); 
}; 
+0

'foreach($ cat as list($ cat2,$ course2))''PHP 5.5' – Baba 2013-03-15 18:35:42

+2

爲什麼你要'一次又一次'重複一個文件? – 2013-03-15 18:36:05

+0

@Baba:你可以認真的做到這一點嗎? – 2013-03-15 18:37:00

回答

0
$categ = array(); 
while ($row = mysql_fetch_array($result)) { 
    $obj = new stdClass(); 
    $obj->cat = $row["CategoryName"]; 
    $obj->course = $row["Course"]; 
    $categ[] = $obj; 
} 

foreach($categ as $thing) 
{ 
    $thing->cat; 
    $thing->course; 
} 

我會推薦這樣的事情。

編輯:甚至更好

$categ = array(); 
while ($obj = mysql_fetch_object($result)) { 
    $categ[] = $obj; 
} 

foreach($categ as $thing) 
{ 
    $thing->cat; 
    $thing->course; 
} 
+0

我已經選擇了該方法中底: 的foreach($ CATEG爲$行){$ 貓= $行[ '貓'] $類別= $行[ '當然'] }; – user2162372 2013-03-15 18:58:58

0

你不能在foreach像使用list()。你需要做的是這樣的:

foreach ($categ as $value){ 
    list($cat2, $course2) = $value; 
} 

編輯:您可以foreach ($categ as list($cat2, $course2)){ PHP 5.5+

+0

謝謝 - 這拋出了錯誤,雖然 – user2162372 2013-03-15 18:57:30

+0

@ user2162372:什麼拋出一個錯誤?它有什麼錯誤? – 2013-03-15 18:58:59

0

我們也可以這樣做:

$categ = array(); 
while ($row = mysql_fetch_array($result)) { 
    $categ[$row["CategoryName"]][] = $row["Course"]; 
} 

陣列將

Array (
    [Dogs] => Array (Kempton Park, Lingfield Park), 
    [Gallops] => Array (Wincanton) 
) 

那麼你可以做:

foreach($categ as $category => $courses) { 
    $courses = array_unique($courses); 
    foreach($courses as $course) { 
     echo $category . ' : ' . $course; //or any other action 
    } 
}