如何在php pdo中生成与密钥对相同的数组值?

snvhrwxg  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(612)

我正在使用php pdo从数据库表中获取选项。

  1. public function fetch_custom_options($type){
  2. $sql = "SELECT option_id, option_name,option_value,type,position FROM ts_options WHERE type=:type";
  3. $stmt = $this->dbConnection->prepare($sql);
  4. $stmt->bindParam(":type", $type, PDO::PARAM_STR);
  5. $stmt->execute();
  6. $rows = $stmt->fetchAll();
  7. return $rows;
  8. }

正如您在查询中看到的,我在同一个表中有两列,如option_name和option_value。我想将每个选项的名称设为键,将每个选项的值设为值,并将其存储在如下数组()中-

  1. public function fetch_custom_options($type){
  2. $sql = "SELECT option_id, option_name,option_value,type,position FROM ts_options WHERE type=:type";
  3. $stmt = $this->dbConnection->prepare($sql);
  4. $stmt->bindParam(":type", $type, PDO::PARAM_STR);
  5. $stmt->execute();
  6. $rows = $stmt->fetchAll();
  7. $custom=array();
  8. foreach($rows as $row){
  9. $custom[] = array($row['option_name']=>$row['option_value']);
  10. }
  11. return $custom;
  12. }

当我使用 option_name 值来访问自定义数组值,然后它给我未定义-

  1. $rows= $getFromPostClass->fetch_custom_options('ad');
  2. foreach($rows as $row)
  3. {
  4. $header_index=$row['header_index'];
  5. }
  6. echo $header_index;

这个 header_index 是一个 option_name 作为密钥存储在第二个数组中。

  1. Notice: Undefined index: header_index in

我的表中有很多值,比如-

  1. option_name , option_value ,type
  2. header_index, 12344 , ad
  3. below_title , 348478 , ad
  4. below_content , 77676 , ad

我不确定,但我会详细说明。我想去商店 option_name 以价值为关键 option_value 值作为数组中的值,使用 foreach() 循环-我将使用名称访问数组值,并获得类似-echo$row['header_index']的值;应显示同一行的选项_值。

dgsult0t

dgsult0t1#

您应该创建关联数组,而不是二维数组。

  1. public function fetch_custom_options($type){
  2. $sql = "SELECT option_id, option_name,option_value,type,position FROM ts_options WHERE type=:type";
  3. $stmt = $this->dbConnection->prepare($sql);
  4. $stmt->bindParam(":type", $type, PDO::PARAM_STR);
  5. $stmt->execute();
  6. $rows = $stmt->fetchAll();
  7. $custom=array();
  8. foreach($rows as $row){
  9. $custom[$row['option_name']]=>$row['option_value']);
  10. }
  11. return $custom;
  12. }
  13. $options= $getFromPostClass->fetch_custom_options('ad');
  14. $headers = $options['header_index'];

相关问题