【问题标题】:Create array with key and value in loop PHP在循环PHP中创建具有键和值的数组
【发布时间】:2015-08-22 23:56:55
【问题描述】:

我正在使用 PDO,尽管有表名,但我设法获取了表列并创建了绑定变量,就像在 ... VALUES (:foo, :bar); 中一样。

我尝试这样做的方法是insert()

public function insert()
{
    // the variable names depend on what table is being used at the moment the script runs.
    // These methods use the PDO `getColumnMeta()` to retrieve the name of each column
    $sql = "INSERT INTO {$this->getTableName()}({$this->getTableColumns()}) "
            . "VALUES ({$this->getTableColumns(true)})";

    // The previous method gets the name of each column and returns a single string, like "foo, bar, [...]"
    // and this function is used to separate each word, with the specified delimiter
    $col = explode(", ", $this->getTableColumns());

    // Now here lays the problem.
    // I already know how to retrieve the columns name as a variable, and
    // how to dynamically create the get method, using `ucfirst()`
    // What I need would be something like this being inside of a
    // loop to retrieve all the separated words from `$col` array.
    $data = array(
        $col[$i] => "\$this->entity->get".ucfirst($col[$i])."()",
    )

    /*
     * From now on, is what I need to do.
     */
    // Lets pretend the column names are "foo, bar".
    $data = array(
        ":foo" => $this->entity->getFoo(),
        ":bar" => $this->entity->getBar()
    )

    // That'd be the final array I need, and then continue with
    $stm = $this->db->prepare($sql);
    $stm->execute($data);        
 }

【问题讨论】:

  • 也贴出相关代码..
  • 请添加您如何创建准备好的语句的代码,以便我们查看您使用了哪些变量等等

标签: php arrays multidimensional-array pdo


【解决方案1】:

您必须遍历 $data 数组并根据您的要求添加函数。 从 `... VALUES (:foo, :bar); 中获取值然后像您在代码中所做的那样展开,然后循环 $col 数组并根据需要向 $data 添加值

foreach($col as $val){
    $method = "get".ucfirst( $val);
    $data[ $val] =  call_user_func(array( $this->entity,$method));
}

上面的代码可以如下工作

$data[':foo'] =  $this->entity->getFoo();
$data[':bar'] =  $this->entity->getBar();

【讨论】:

  • 你好。我编辑了我的问题,并试图让我更清楚地了解我的需求。谢谢你。 :)
  • 请替换 $data = array( $col[$i] => "\$this->entity->get".ucfirst($col[$i])."()", ) 用我的代码 $data[$temp] = call_user_func(array( $this->entity,$method));并尝试。
猜你喜欢
  • 1970-01-01
  • 2020-05-16
  • 1970-01-01
  • 2016-07-29
  • 1970-01-01
  • 2017-08-31
  • 2012-03-18
  • 1970-01-01
  • 2013-12-22
相关资源
最近更新 更多