Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Hi I was wondering how to create an array with key value pairs from my other array which is an array consisting of values read in from a DB table.

Heres the code:

$query1 = "SELECT phone, id FROM table1 GROUP BY id";
$result1 = $mysqli->query($query1);

while($rows = $result1->fetch_assoc()) {

}

In order to see the array I used fwrite and var_export

Heres the var_export($row,1):

array('phone' => 123, 'id' => 456)  
array('phone' => 246, 'id' => 789)  

What am looking for is to create another array using those values to look like this:

array(  
   123 => 456  
   246 => 789)  
share|improve this question

1 Answer

up vote 4 down vote accepted

Use this:

$newArray = array();
while($rows = $result1->fetch_assoc()) {
    $newArray[$rows['phone']] = $rows['id'];
}

The new array will then look like this:

array(  
   123 => 456  
   246 => 789
)
share|improve this answer
3  
Note the fetch mode: fetch_assoc, best use $newArray[$rows['phone']] = $rows['id'] – Elias Van Ootegem Aug 19 at 11:11
@EliasVanOotegem - thanks, just updated! – Joe Aug 19 at 11:13
Thanks very helpful – lawrence Aug 19 at 11:26

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.