-3

I'm having a problem trying to make an associative array that would looked like :

Array(
      Array('111.01.0040' => 'PEMBENAHAN PIPA TURBIN'),
      Array('111.01.0041' => 'PENGELASAN UNVIL'),
      Array('111.01.0042' => 'BONGK.PASANG PINION/LAMAK SPIE')
      );

from a table that looked like

No    | kdbr        | nmbr
1     | 111.01.0040 | PEMBENAHAN PIPA TURBIN
2     | 111.01.0041 | PENGELASAN UVIL
3     | 111.01.0042 | BONGK.PASANG PINION/LAMAK SPIE

all i can do is having an array that looked like

Array ( [0] => Array (
    [111.01.0040] => PEMBENAHAN PIPA TURBIN
    [111.01.0041] => PENGELASAN UNVIL
    [111.01.0042] => BONGK.PASANG PINION/LAMAK SPIE);

and my code is like

$dbc = mysqli_connect('localhost', '*****', '*****', '*****');
$query = "SELECT kdbr, nmbr FROM tb_master_barang";
$result = mysqli_query($dbc, $query);
$data_array = array();
while ($row = mysqli_fetch_assoc($result)) {
    $data_array[$row['kdbr']] = $row['nmbr'];
}

is it possible having array like what i want to make by getting data from database? can anyone help me?

thanks :)

Oswald
  • 31,254
  • 3
  • 43
  • 68
  • `$data_array[] = array($row['kdbr'] => $row['nmbr']);` – deceze Aug 11 '14 at 07:59
  • one thing again to ask, in my table `kdbr` is defined as varchar, but at array it's out as `["111.01.0041"]` and not `"111.01.0041"`, how can i remove the `[]` tag? – ryuusoultaker Aug 11 '14 at 08:33
  • When is what exactly output as `["..."]`? – deceze Aug 11 '14 at 08:37
  • i'm sorry, i was doing on a wrong path for a long time... what i need is creating an array that like `array(array('kdbr'=>"111.01.0041", nmbr => PENGELASAN UNVIL)` instead of what i write up there.. – ryuusoultaker Aug 11 '14 at 08:52

1 Answers1

0

It's possible, but you have thought about it all backwards.

Array (
     Array(A => B)
     Array(C => D)
)

is actually

Array (
    [0] => Array(A => B)
    [1] => Array(C => D)
)

This means you have to create a new array each time if you want the Array (x => y) effect.

while ($row = mysqli_fetch_assoc($result)) {
    $data_array[$row['no']] = array($row['kdbr'] => $row['nmbr']);
}

or if you don't want it ordered by $row['no'] but instead just want it added to the array by the way you order your SQL-query:

while ($row = mysqli_fetch_assoc($result)) {
    $data_array[] = array($row['kdbr'] => $row['nmbr']);
}
user2687506
  • 789
  • 6
  • 21