2013-05-09 136 views
2

我想從表中獲取數據到數組中,並且我不想使用foreach循環來處理速度問題。如何使用foreach循環從表中獲取數據

我嘗試使用

function getRowsAssoc() 
{ 
    $ret = array(); 
    while (($temp = mysql_fetch_assoc($this->result)) !== FALSE) 
    { 
     if (count($temp) > 0) 
     { 
      $ret[] = $temp; 
     } 
    } 
    if (count($ret) > 0) 
    { 
     return $ret; 
    } 
    else 
    { 
     return FALSE; 
    } 
} 

然而,這導致對。

Array (
    [0] => Array ([MySKU] => BB1-3500-48 [UPC] => 721343100171) 
    [1] => Array ([MySKU] => BC7-3501-19 [UPC] => 721343103516) 
    [2] => Array ([MySKU] => BC7-3501-95 [UPC] => 721343103523) 
    [3] => Array ([MySKU] => BB1-3502-12 [UPC] => 721343114000) 
    [4] => Array ([MySKU] => bc7-2370-03 [UPC] => 721343121602) 
) 

這個問題是不是返回副教授陣列它添加在它的上面有編號數組所以現在我無法從該項目代碼的數據。

我想獲得這樣的

Array (
     [MySKU] => BB1-3500-48 [UPC] => 721343100171 
     [MySKU] => BC7-3501-19 [UPC] => 721343103516 
     [MySKU] => BC7-3501-95 [UPC] => 721343103523 
     [MySKU] => BB1-3502-12 [UPC] => 721343114000 
     [MySKU] => bc7-2370-03 [UPC] => 721343121602 
    ) 
+0

注:使用庫MySQLi或PDO,而不是MySQL的(棄用的5.5)。 – Aleph 2013-05-09 13:51:58

+0

「對於速度問題」...我不認爲在foreach和while或者之間有任何速度差異,至少有一個人類可以察覺的速度問題 – aleation 2013-05-09 13:56:39

+0

'foreach'用於迭代現有數組。在這種情況下,你正在用'while'構建數組。你不能用'foreach'替換它,因爲沒有你可以使用它的數組。 – Lukas 2013-05-09 14:01:39

回答

1

指定密鑰:

所有你應該知道的
function getRowsAssoc() 
{ 
    $ret = array(); 
    while (($temp = mysql_fetch_assoc($this->result)) !== FALSE) 
    { 
     if (count($temp) > 0) 
     { 
      $ret[$temp["MySKU"]] = $temp; 
     } 
    } 
    if (count($ret) > 0) 
    { 
     return $ret; 
    } 
    else 
    { 
     return FALSE; 
    } 
} 
+0

這工作!謝謝 – MarkGreen 2013-05-09 14:37:42

0

首先,如何結果陣列的結構應該。

對於結構類似

Array 
(
    [MySKU-x] => UPC-x 
    [MySKU-y] => UPC-y 
    [MySKU-z] => UPC-z 
) 

您可以使用此:

function getRowsAssoc() 
{ 
    $return = array(); 
    while (($temp = mysql_fetch_assoc($this->result)) !== false) 
    { 
     if (count($temp) > 0) 
     { 
      $return[$temp['MySKU']] = $temp['UPC']; 
     } 
    } 
    if (count($return) > 0) 
    { 
     return $return; 
    } 
    else 
    { 
     return false; 
    } 
} 
相關問題