首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >如何在PHP PDO中使相同的数组值作为键对?

如何在PHP PDO中使相同的数组值作为键对?
EN

Stack Overflow用户
提问于 2021-07-27 00:47:23
回答 1查看 51关注 0票数 0

我正在使用PHP PDO从我的数据库表中获取选项。

代码语言:javascript
代码运行次数:0
运行
复制
 public function fetch_custom_options($type){
    $sql = "SELECT option_id, option_name,option_value,type,position FROM ts_options WHERE type=:type";
    $stmt = $this->dbConnection->prepare($sql);
    $stmt->bindParam(":type", $type, PDO::PARAM_STR);
    $stmt->execute();
    $rows = $stmt->fetchAll();
    return $rows;
}

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

代码语言:javascript
代码运行次数:0
运行
复制
public function fetch_custom_options($type){
    $sql = "SELECT option_id, option_name,option_value,type,position FROM ts_options WHERE type=:type";
    $stmt = $this->dbConnection->prepare($sql);
    $stmt->bindParam(":type", $type, PDO::PARAM_STR);
    $stmt->execute();
    $rows = $stmt->fetchAll();
    $custom=array(); 
    foreach($rows as $row){ 
        $custom[] = array($row['option_name']=>$row['option_value']);
    }
    return $custom;
}

当我使用option_name值访问自定义数组值时,它给了我未定义的-

代码语言:javascript
代码运行次数:0
运行
复制
$rows= $getFromPostClass->fetch_custom_options('ad');
foreach($rows as $row) 
{ 
    $header_index=$row['header_index'];
}
echo $header_index; 

header_index是作为密钥存储在第二数组中的密钥( option_name )。

代码语言:javascript
代码运行次数:0
运行
复制
Notice: Undefined index: header_index in

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

代码语言:javascript
代码运行次数:0
运行
复制
option_name , option_value ,type 
header_index, 12344   ,  ad 
below_title , 348478   ,  ad 
below_content , 77676  ,  ad  

我对此不是很确定,但我会详细说明。我希望使用foreach()循环将option_name值作为键存储在数组中,并将option_value值作为值存储在数组中-我将使用名称访问数组值,并获得类似于回显$foreach()的行‘option_value _option_value’;应该显示同一行的索引。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-27 01:03:06

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

代码语言:javascript
代码运行次数:0
运行
复制
public function fetch_custom_options($type){
    $sql = "SELECT option_id, option_name,option_value,type,position FROM ts_options WHERE type=:type";
    $stmt = $this->dbConnection->prepare($sql);
    $stmt->bindParam(":type", $type, PDO::PARAM_STR);
    $stmt->execute();
    $rows = $stmt->fetchAll();
    $custom=array(); 
    foreach($rows as $row){ 
        $custom[$row['option_name']]=>$row['option_value']);
    }
    return $custom;
}

$options= $getFromPostClass->fetch_custom_options('ad');
$headers = $options['header_index'];
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68533646

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档