将列添加到现有的 php 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12286272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:14:13  来源:igfitidea点击:

Adding columns to existing php arrays

phparraysjson

提问by Elcid_91

Using PHP let's assume that I have successfully read a record from a MySQL table using the fetch_object method and I am holding the row data in a variable call $output:

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

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

If I wanted to add two additional fields: "cls" and "parentID" to $output as if they were apart of $row, how would I accomplish this? Thanks!

如果我想向 $output 添加两个额外的字段:“cls”和“parentID”,就好像它们是 $row 的一部分,我将如何实现?谢谢!

回答by nickb

Loop through the array by reference and add what you want after the while loop:

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

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

You can also do this within the while loop:

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

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

回答by Marc B

Since you changed the code snippet in your question, try this instead now (updated version):

由于您更改了问题中的代码片段,请立即尝试(更新版本):

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

回答by Ledahu

$myArray=array_merge($myArray,$myAddArray);

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

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

or use array_push()

或使用 array_push()

apply it in the foreach/while loop for each row.

将其应用于每行的 foreach/while 循环。