0

I have three variables retrieved from a database and I would like the first variable to be the key for the second variable and for that second variable to be the key for the third variable. In essence a two-dimensional array.

 while($row = $statement->fetch(PDO::FETCH_ASSOC))
    {
         $unit_id = $row['id'];
          $unit_code = $row['unit_name'];
           $unit_description = $row['unit_description'];

         $units = [$unit_id => $unit_code];
         $units += [$unit_code => $unit_description];

    }
    return $units;
jon
  • 407
  • 4
  • 13

4 Answers4

1

Yess you can do this.

$array = [
 'data' => 'my data'
];

now you can do this simply

$array['anotherArray'] = $anotherArray;
FULL STACK DEV
  • 15,207
  • 5
  • 46
  • 66
1

If "id", "unit_name" and "unit_description" are respectively the first, second and third value of the database, this is the code:

while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
    $units[$row['id']][$row['unit_name']] = $row['unit_description'];


}
return $units;
Giacomo M
  • 4,450
  • 7
  • 28
  • 57
1

You can simply make like this

<?php
    $unit_id = 'id';
    $unit_code = 'unit_name';
    $unit_description = 'unit_description';

    $units[$unit_id] = [$unit_code=>$unit_description];
    //$units[$unit_id][$unit_code] = $unit_description;
    print_r($units);
?>

Live demo : https://eval.in/880865

Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
0

If array consists of key, value parts (associative arrays), which your case is like that, you just need to:

$data[$key] = $value;

So in your case it would be:

$units[$unit_code] = $unit_description;

If your arrays' keys are indexed, then using array_push can do the job too:

array_push($units, $unit_description);
Alireza
  • 6,497
  • 13
  • 59
  • 132