HackerManiac
HackerManiac

Reputation: 243

Push key and value into associative array

I want to push data and key into associative array. I fetch from database something like this -->

 $data=mysqli_query($con,"SELECT id,name FROM names ");
    while($row = mysqli_fetch_Assoc($data)){
       $id[] = $row['id'];
       $name[] = $row['name'];
 }

if this fethes something like this ->

$id = {2,4,8,20} and $name={'David','Goliath','ronaldo','messi'}

i want an array like this

$_SESSION['list'] = array(
 'David' => 2,
 'Goliath' => 4,
  'ronaldo'  =>8,
  'messi' => 20
);

how will i push those values in an array ?

Upvotes: 0

Views: 1610

Answers (2)

Ray
Ray

Reputation: 41428

Simple.

 $_SESSION['list'] = array();

 while($row = mysqli_fetch_Assoc($data)){
    $_SESSION['list'][$row['name']] = $row['id'];
 }

Upvotes: 2

marekful
marekful

Reputation: 15351

You can do something like this:

$result = array();
$data=mysqli_query($con,"SELECT id,name FROM names ");
    while($row = mysqli_fetch_Assoc($data)){
       $result[$row['name']] = $row['id'];
}

$_SESSION['list'] = $result;

Upvotes: 2

Related Questions