I have the following table:
columns, id , name , value
I want to get from pdo result like the following:
array = ["name1", "name2" ,"name3"]
and each "name" array will hold the value
so to get the value of name 1 I will do something like: $array["name1"]["value"]
and I will get the value by name and not by id
I tried to that with :
$sth = $this->db->prepare("SELECT name ,value FROM table");
$result = $sth->fetchAll(FETCH_ASSOC);
but it returned index array and only by id I can get the name and value
To do this, you need to get an associative array of this type:
$list= array(
'name1'=>'value1',
'name2'=>'value2',
'name3'=>'value3'
)
and not the simple type you mentioned:
array = ["name1", "name2" ,"name3"]
So you follow this procedure:
$res = $this->db->prepare("SELECT name,value FROM table");
$res->execute($params);
$fetch= $res->fetchAll(PDO::FETCH_ASSOC);
$list = array();
for ($i = 0; $i < count($fetch); $i++) {
$list[$fetch[$i]['name']] = $fetch[$i]['value'];
}
$res->closeCursor();
You must make new array with converted data:
$sth = $this->db->prepare("SELECT name, value FROM table");
$result = array_values($sth->fetchAll(FETCH_ASSOC));
$new = [];
foreach($result as $ar) {
$new[$ar['name']] = $ar['value'];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.