0

在下面的代码中,print_rwhile 循环中的第一个打印不同的故事内容。我遇到的问题是第二条语句从数组中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.
        )
4

1 回答 1

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
    )
于 2012-12-02T19:22:33.137 回答