2012-12-02 45 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