首页 > 解决方案 > 将新的组合数组推送到 PHP 数组

问题描述

我有以下代码。这会从 SQL 表(“db”)中获取字段,并准备好在数据表(“dt”)中使用它们。

$columns = array(
  array( 'db' => 'Author', 'dt' => 'authors'),
  array( 'db' => 'Editor', 'dt' => 'editor')
);

它打印这个

[{"authors":"John Smith; Paul Phillips","editors":"Robert Fox"},...]

现在我想将第三个数组 ( people) 推送到columns,它结合了前两个数组,但不替换它们,比如

[{"authors":"John Smith; Paul Phillips","editors":"Robert Fox","people": "John Smith: Paul Phillips; Robert Fox"},...]

标签: phpsqlarraysdatatable

解决方案


如果它只是您尝试添加到 $columns 的数组,请使用array_merge()

$columns = array(
    array( 'db' => 'Author', 'dt' => 'authors'),
    array( 'db' => 'Editor', 'dt' => 'editor')
);
$person = array( 'db' => 'Person', 'dt' => 'person');

$newArray = array_merge($columns, $person);

结果应如下所示:

array(4) {
  [0]=>
  array(2) {
    ["db"]=>
    string(6) "Author"
    ["dt"]=>
    string(7) "authors"
  }
  [1]=>
  array(2) {
    ["db"]=>
    string(6) "Editor"
    ["dt"]=>
    string(6) "editor"
  }
  [2]=>
  array(2) {
    ["db"]=>
    string(6) "Person"
    ["dt"]=>
    string(6) "person"
  }
}

推荐阅读