Can I make an associative array from two columns? I want column A as key and column B as value.
-------------
| id | name |
-------------
| 1 | sky |
-------------
| 2 | space |
I want a function that make result like this:
$ary=array('1'=>'sky','2'=>'space', ... );
Is any php function exist about this matter?
I'm using php, mysql and codeigniter.
$ary = array();
while ($row = $stmt->fetch_assoc()) {
$ary[$row['id']] = $row['name'];
}
Even though you are using codeigniter, you are not required to use codeigniter's libraries. If you are willing to implement a PDO implementation you can do something like this in native PHP:
$stmt = $db->query("select id, name from mytable");
$results = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
There would be less overhead this way than with some other implementations, but it depends if you want to use PDO.
foreach($rows as $key => $value){
$arr[$key] = $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.