【问题标题】:Add additional value to array built from variables in PHP为从 PHP 中的变量构建的数组添加附加值
【发布时间】:2015-05-06 02:15:55
【问题描述】:

我在 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_ids 生成的。

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

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

【问题讨论】:

    标签: php mysql sql arrays pdo


    【解决方案1】:
    $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

    【讨论】:

    • @jonmrich 我用一个例子编辑,别忘了检查答案是否正确;-)
    • 感谢您提供额外的见解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 2014-04-21
    相关资源
    最近更新 更多