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

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

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

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。我想将每个选项的名称设为键,将每个选项的值设为值,并将其存储在如下数组()中-

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 值来访问自定义数组值,然后它给我未定义-

$rows= $getFromPostClass->fetch_custom_options('ad');
foreach($rows as $row) 
{ 
    $header_index=$row['header_index'];
}
echo $header_index;

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

Notice: Undefined index: header_index in

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

option_name , option_value ,type 
header_index, 12344   ,  ad 
below_title , 348478   ,  ad 
below_content , 77676  ,  ad

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

dgsult0t

dgsult0t1#

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

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'];

相关问题