Anggie Ari Widhia
Anggie Ari Widhia

Reputation: 73

Looping fails only iterate the last sequence of data in arrays

I have some lines of data on a table as shown below :

+-------------------+-------+
| criteria          | value |
+-------------------+-------+
| Pengalaman Kerja  |     4 |
| Pendidikan        |     3 |
| Usia              |     5 |
| Status Perkawinan |     2 |
| Alamat            |     6 |
| Pengalaman Kerja  |     3 |
| Pendidikan        |     1 |
| Usia              |     4 |
| Status Perkawinan |     2 |
| Alamat            |     1 |
+-------------------+-------+
10 rows in set (0.00 sec)

When I iterate through data above in PHP using MySQLI fetch_object, I want to create new arrays that will end up like this :

Array
(
    [Pengalaman Kerja] => Array
        (
            [1] => 4
            [2] => 3
        )

    [Pendidikan] => Array
        (
            [1] => 3
            [2] => 1
        )

    [Usia] => Array
        (
            [1] => 5
            [2] => 4
        )

    and so on..
)

I've been hardly trying and boiling up my head with these array things and ended up in code as shown below :

 $result      = $db->query($sql);

 while($row=$result->fetch_object()){

   if(!isset($isi[$row->criteria])){
     $isi[$row->criteria] = array();
   }

   $isi[$row->criteria] = 
   array(1 => $data[$row->name][$row->criteria]);  

   $number = count($data);
   for ($i=2; $i<=$number; $i++) { 
      array_push($isi[$row->criteria], $row->value);
   }
}

The wrapping arrays are correct, errors are in the values of each wrapping array. The code above only took the last sequence of data :

 Array
 (
    [Pengalaman Kerja] => Array
       (
            [1] => 4
            [2] => 4
       )

    [Pendidikan] => Array
       (
            [1] => 3
            [2] => 3
       )

    [Usia] => Array
       (
            [1] => 5
            [2] => 5
       )

    and so on..
)

Could you guys help me elaborating what were wrong things in my code and how to fix it to get the expected result?

Thank you in advance.

Edit :

This is how I loop through the data

Upvotes: 1

Views: 28

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157999

if(!isset($isi[$row->criteria])){
     $isi[$row->criteria] = array();
}
$isi[$row->criteria][] = $row->value;

Upvotes: 1

Related Questions