php - 向从 PHP 中的变量构建的数组添加附加值

标签 php mysql sql arrays pdo

我在 PHP 中有以下代码:

$stmt2 = $dbh->prepare("select GROUP_CONCAT( cohort_id SEPARATOR ',') as cohort_id from ( select distinct cohort_id from table_cohorts) as m"); 
$stmt2->execute(); 
$row2 = $stmt2->fetch();
$cohorts_allowed = explode(",",$row2["cohort_id"]);
$value = array ('amount', $cohorts_allowed );

$cohorts_allowed 给我类似“database_percent, national_percent”的信息。它是从我的数据库中所有可能的 cohort_id 生成的。

我需要做的是获取所有这些并将附加值“amount”(不在我的数据库中)添加到数组中。

我该怎么做。您可以看到我在上面代码的最后一行尝试这样做,但显然那行不通。

最佳答案

$cohorts_allowed = explode(",",$row2["cohort_id"]);
$cohorts_allowed['amount'] = 'amount' ;

$cohorts_allowed = explode(",",$row2["cohort_id"]);
$cohorts_allowed[] = 'amount' ;

这是如何工作的:

<pre>
<?php

$row2["cohort_id"] = "database_percent, national_percent";
$cohorts_allowed = explode(",",$row2["cohort_id"]);

print_r($cohorts_allowed);

/* output
Array
(
    [0] => database_percent
    [1] =>  national_percent

)
* The last index is 1
*/

$cohorts_allowed[] = 'amount' ;

print_r($cohorts_allowed);

/* output
Array
(
    [0] => database_percent
    [1] =>  national_percent
    [2] => amount
)
* The last index is 2 (after 1) and have the value amount.
* 
*/

?>
</pre>

你可以读入:

http://php.net/manual/en/language.types.array.php

关于php - 向从 PHP 中的变量构建的数组添加附加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28865519/

相关文章:

php - Symfony 与 CakePHP : which one is closest to PHP

php - 多张图片上传不移动目录中的文件

php - 我是否正确尝试使用 PHP 更新数据库中的记录?

sql - 使用 dbms_random.value 和指定的比例创建

java - 准备语句错误

来自sql db的php动态css下拉菜单

php - Yii 添加另一个 $content 到模板

php - 无法使用 simplexml_load_file 进入目录

php - 使用 PHP 将值插入服务器

c# - Dapper LIKE 查询 MySql 是否安全,可以防止 Sql 注入(inject)?