Creating Variables in Foreach Loop

Ada kalanya programmer menginginkan membuat variable yang otomatis dari query SQL database, sehingga lebih efisien dalam membuat program.

Sebagai contoh, marilah kita persiapkan terlebih dahulu database nya. sebagai info saya menggunakan framework CodeIgniter.
Ikutilah langkah-langkah berikut:

1. Buat table beserta datanya.

CREATE TABLE IF NOT EXISTS `data_training` (
  `id` int(11) NOT NULL,
  `x1` varchar(5) NOT NULL,
  `x2` varchar(11) NOT NULL,
  `x3` int(11) NOT NULL,
  `classroom` varchar(3) NOT NULL
  ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;
 
  INSERT INTO `data_training` (`id`, `x1`, `x2`, `x3`, `classroom`) VALUES
  (1, ‘Yes’, ‘Single’, 125, ‘No’),
  (2, ‘No’, ‘Married’, 100, ‘No’),
  (3, ‘No’, ‘Single’, 70, ‘No’),
  (4, ‘Yes’, ‘Married’, 120, ‘No’),
  (5, ‘No’, ‘Divorce’, 95, ‘Yes’),
  (6, ‘No’, ‘Married’, 60, ‘No’),
  (7, ‘Yes’, ‘Divorce’, 220, ‘No’),
  (8, ‘No’, ‘single’, 85, ‘Yes’),
  (9, ‘No’, ‘Married’, 75, ‘No’),
  (10, ‘No’, ‘Single’, 90, ‘Yes’);

2. Script pada Model

public function countclassnb(){
  //select class, count(class) from data_training GROUP by class
  $this->db->select(‘classroom’);
  $this->db->select(‘count(classroom) as countclass’);
  $this->db->group_by(“classroom”);
  $query = $this->db->get(‘data_training’);
  return $query->result();
  }

3. Script pada controller

$dataPYYesNo=$this->naivebayes_model->countclassnb();
$count = 0;
foreach ($dataPYYesNo as $k) {
 $count++;
 $new_data[“classroom”.$count] = $k->classroom;
}

extract($new_data);
echo $classroom1.”<br />”;
echo $classroom2.”<br />”;

4. Outputnya

No
Yes

5. Done 😀

Sekian Terimakasih,
Sumber : https://www.daniweb.com/programming/web-development/threads/356768/creating-variables-in-foreach-loop-
Regards,

Okto Alhamda Putra

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s