向 PHP 中的变量构建的数组添加附加值
Add additional value to array built from variables in PHP
我在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>
您可以阅读:
我在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>
您可以阅读: