手动将元素添加到fetch数组的末尾

时间:2014-01-13 20:23:20

标签: php arrays

我找不到任何答案,我目前没有想法。

我有以下循环,它存储在一个数组中,即数据库提取的资源

    $posts = array();
      while ($row = mysql_fetch_assoc($result)){
          $posts[] = $row;
      }

          return $posts;
var_dump上的

$posts输出以下内容:

array (size=1)
  0 => 
    array (size=6)
      0 => 
        array (size=4)
          'items' => string '16' (length=2)
          'item_name' => string 'Blu-ray Disc Player BDP-S1100' (length=29)
          'item_price' => string '3500.00' (length=7)
          'avatar' => string 'gallery/miniaturas/cf6772a2c2b72d575f11b41aee5a2f47.png' (length=55)
      1 => 
        array (size=4)
          'items' => string '16' (length=2)
          'item_name' => string 'Blu-ray Disc Player BDP-S1100' (length=29)
          'item_price' => string '3500.00' (length=7)
          'avatar' => string 'gallery/miniaturas/a6bf82f38d930567a759eaef91d6fb30.png' (length=55)

我想做的是使用键添加一(1)个静态值"键入"和价值" 1"到每个数组的末尾,var_dump将如下所示:

array (size=1)
  0 => 
    array (size=6)
      0 => 
        array (size=4)
          'items' => string '16' (length=2)
          'item_name' => string 'Blu-ray Disc Player BDP-S1100' (length=29)
          'item_price' => string '3500.00' (length=7)
          'avatar' => string 'gallery/miniaturas/cf6772a2c2b72d575f11b41aee5a2f47.png'
          'type' => int 1
   (length=55)
      1 => 
        array (size=4)
          'items' => string '16' (length=2)
          'item_name' => string 'Blu-ray Disc Player BDP-S1100' (length=29)
          'item_price' => string '3500.00' (length=7)
          'avatar' => string 'gallery/miniaturas/a6bf82f38d930567a759eaef91d6fb30.png'
          'type' => int 1
   (length=55)

有可能吗?如果是的话,怎么样?

感谢。

3 个答案:

答案 0 :(得分:3)

在添加之前,只需修改$row即可。避免任何额外开销

$posts = array();
while ($row = mysql_fetch_assoc($result)){
      $row['type'] = 1;
      $posts[] = $row;
}

答案 1 :(得分:2)

您应该能够向数组添加任意键,其值为1,如下所示:

$posts = array();
while ($row = mysql_fetch_assoc($result)){
      $posts[] = $row;
      $posts[count($posts)-1]["type"] = 1;
}

return $posts;

或者,如果您可以编辑SQL查询,也可以在选择的末尾添加1 as type,然后您的数据库将为您添加额外的列。

答案 2 :(得分:0)

这应该有效:

while ($row = mysql_fetch_assoc($result)){
    $posts[] = array_merge($row, array(
        'type' => 1,
    ));
}

或者,或者,修改SQL查询以自动添加字段:

$sql = 'SELECT *, 1 AS type FROM table';