Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
It'll come out of your mysql query as an array/object that you loop through using a while statement. If you then need to further put it into an array just insert it inside your while. But in a dataset as simple as yours I can see no reason to array it over just looping –  Dave Jul 16 '13 at 8:46
1  
There is no single function that connects to a database, retrieves data and formats it into an array with one column as a key and another as a value; you'll need to write it yourself.... have you tried? which part are you having problems with? –  Mark Baker Jul 16 '13 at 8:47

2 Answers 2

$ary = array();
while ($row = mysqli->fetch_assoc()) {
    $ary[$row['id']] = $row['name'];
}
share|improve this answer
foreach($rows as $key => $value){
    $arr[$key] = $value;
}
share|improve this answer
2  
For large datasets, it would result in better performance to fetch each single row instead of fetching them all and iterate over the result set. –  feeela Jul 16 '13 at 8:48

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.