【问题标题】:Adding columns to existing php arrays将列添加到现有的 php 数组
【发布时间】:2012-08-30 10:59:55
【问题描述】:

使用 PHP 假设我已经使用 fetch_object 方法成功地从 MySQL 表中读取了一条记录,并且我将行数据保存在一个变量调用 $output 中:

while($row = $result->fetch_object())
{
   $output[] = $row;
}

如果我想在 $output 中添加两个附加字段:“cls”和“parentID”,就好像它们是 $row 的一部分一样,我该如何完成呢?谢谢!

【问题讨论】:

    标签: php arrays json


    【解决方案1】:

    由于您更改了问题中的代码 sn-p,现在试试这个(更新版本):

    while(...) {
       $row->cls = ...;
       $row->parentID = ...;
       $output[] = $row;
    }
    

    【讨论】:

    • $output 是一个多维数组,因此 $output['cls'] 将无法正常工作。而且我相信 OP 正在处理一组对象(因此 fetch_object() 调用),所以 [] 表示法也会失败。
    • 如果我 json_encode(),它将字段放在行数据数组之外:
    • 好吧,当我写这篇文章时,你的问题中没有$output[]。然后,您必须先将新数据添加到 $row,然后再将其分配给 $output。现在修正答案。
    【解决方案2】:

    通过引用循环遍历数组并在while循环之后添加你想要的:

    foreach( $output as &$row) {
        $row->cls = 0;
        $row->parentID = 1;
    }
    

    您也可以在 while 循环中执行此操作:

    while($row = $result->fetch_object()) {
        $row->cls = 0;
        $row->parentID = 1;
        $output[] = $row;
    }
    

    【讨论】:

    • 感谢 nickb - 一如既往的完美解决方案。
    • 很好的解决方案,我正在使用它并寻找一种方法来例如获取 $output[0]->parentID 的数据,如何实现?
    • 如果出现以下错误怎么办:Attempt to assign property 'cls' of non-object?
    【解决方案3】:
    $myArray=array_merge($myArray,$myAddArray);
    

    https://www.php.net/manual/en/function.array-merge.php

    或使用 array_push()

    在 foreach/while 循环中为每一行应用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-13
      • 2016-05-03
      • 1970-01-01
      • 2021-09-30
      • 2016-10-16
      相关资源
      最近更新 更多