简体   繁体   中英

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 ?

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;

Simple.

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM