2012-12-02 76 views
0

在以下代碼中,while循環中的第一個print_r將打印不同的故事內容。我遇到的問題是第二條print_r聲明從$stories陣列中反覆產生了完全相同的故事。將內容壓入陣列

$stories = array(); 

while($row = mysql_fetch_array($result)){ 
    $story->name  = $row['Name']; 
    ... 
    $story->date  = $row['Date']; 

    print_r($story); //for testing 
    array_push ($stories , $story); 
} 

print_r($stories); 

編輯: 有人問命令行輸出,但這是一個託管帳戶。如果上面沒有明確,但:

從內環路:

(
    [id] => 9370 
    [name] => Five Below, Inc. 
    ... 
) 
stdClass Object 
( 
    [id] => 9362 
    [name] => Peregrine Pharmaceuticals Inc. 
    ... 
) 
stdClass Object 
(
    [id] => 9363 
    [name] => Mitel Networks Corporation 
) 
... 
stdClass Object 
(
    [id] => 9370 
    [name] => Five Below, Inc. 
    ... 
) 

循環後:

Array 
(
    [0] => stdClass Object 
     (
      [id] => 9370 
      [name] => Five Below, Inc. 
      ... 
     ) 
    [1] => stdClass Object 
     (
      [id] => 9370 
      [name] => Five Below, Inc. 
     ) 
    [2] => stdClass Object 
     (
      [id] => 9370 
      [name] => Five Below, Inc. 
     ) 
+2

控制檯/ phpMyAdmin的執行查詢,並添加輸出到你的問題 –

+1

第二'print_r'在循環之外,'$ stories'在循環內被賦值 - 它應該每次都不一樣?請提供更多的解釋和一些你想要實現的例子。 – poplitea

+0

@ WebnetMobile.com,數據庫和代碼在託管帳戶上運行。離題:我想知道是否應該每次重置故事變量。 – Roger

回答

1

看來問題就出在$story。我製造的測試情況下的代碼:

$rows = array(
     array('Name'=>'1', 'Date'=>'21'), 
     array('Name'=>'4', 'Date'=>'24'), 
); 

$stories = array(); 

foreach($rows as $row) { 
    $story->name  = $row['Name']; 
    $story->date  = $row['Date']; 

    array_push($stories , $story); 
} 

print_r($stories); 

產生

[0] => stdClass Object 
    (
     [name] => 4 
     [date] => 24 
    ) 
[1] => stdClass Object 
    (
     [name] => 4 
     [date] => 24 
    ) 

這是錯誤的。但是加入unset($story);,並有新的對象創建的每個時間,解決了這個問題:

$rows = array(
     array('Name'=>'1', 'Date'=>'21'), 
     array('Name'=>'4', 'Date'=>'24'), 
); 

$stories = array(); 

foreach($rows as $row) { 
    unset($story); // replace with whatever code you use to create new object 
    $story->name  = $row['Name']; 
    $story->date  = $row['Date']; 

    array_push($stories , $story); 
} 

print_r($stories); 

給出正確的:

[0] => stdClass Object 
    (
     [name] => 1 
     [date] => 21 
    ) 

[1] => stdClass Object 
    (
     [name] => 4 
     [date] => 24 
    ) 
+0

謝謝。這解決了它! – Roger