我正在使用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。我想让每个数组作为键,每个数组作为值,并将其存储在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
我对此不是很确定,但我会详细说明。我希望使用foreach()
循环将option_name
值作为键存储在数组中,并将option_value
值作为值存储在数组中-我将使用名称访问数组值,并获得类似于回显$foreach()
的行‘option_value _option_value’;应该显示同一行的索引。
发布于 2021-07-27 01:03:06
您应该创建关联数组,而不是二维数组。
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'];
https://stackoverflow.com/questions/68533646
复制相似问题