将内容推送到数组中

时间:2012-12-02 19:03:05

标签: php

在以下代码中,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.
        )

1 个答案:

答案 0 :(得分: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
    )