2013-02-19 113 views
0

我已經創建了一個陣列使用的第n項,具體如下:在PHP數組

$results = array(); 
do { 
    $results[] = $row_products; 
} while ($row_products = mysql_fetch_assoc($products)); 

print_r($results); 

這會打印出數組是這樣的:

Array ( 
[0] => Array ( 
     [productName] => product1 
     ) 
[1] => Array ( 
     [productName] => product2 
     ) 
[2] => Array ( 
     [productName] => product3 
    ) 

我想現在用說第二在另一個mysql查詢中的數組中的項目。

但我無法定義它。我試過

$results[1]; 

但這不起作用。 所以實際上,如果我回顯第二項,它會打印'product2'。

回答

2

你應該學會的基礎知識有關數組的位置:http://www.php.net/manual/en/language.types.array.php

您正在使用嵌套數組,所以你有這樣的訪問:

echo $results[1]['productName']; 

另一種解決方案是使用$results[] = $row_products['productName'];,然後僅回顯$results[1]

此外,您應該使用while循環而不是do/while循環,因爲$ row_products似乎沒有爲第一次迭代定義。

while ($row_products = mysql_fetch_assoc($products)) { 
    $results[] = $row_products; 
} 
+0

輝煌,謝謝! :) – 2013-02-19 09:21:36

0

試試這個:

echo $results[1]['productName'] ; 

$results[1]是一個數組,如果你想看到陣列print_r($results[1]);