Search code examples
phpmysqlserialization

Issue With An Unserialized Array display in A Loop


Referring to my question: Displaying Serialized Array PHP MYSQL

I have a serialized array stored in MYSQL. I am unserializing and then displaying in table using below code. The code works fine but values are merged in each row. Suppose, ist row had value 3 and second row had value 4 then ist row display 3, which is fine but second row shows 3,4 and similarly, ist row values are merged with other row values. Please assist.

Thanks

Code:

$abc='';
foreach($result as $row)
  {
  $fine_types = unserialize($row['fine_type']);
  echo "<td>";
    foreach ($fine_types as $fine_type) {
            $abc .="<div dir='rtl' lang='ar' class='fntype'> ".$fine_type.'</div>';
        //$r=implode(',')
    }
    echo "</td>";
  

 `$output .= '
    <tr>
            <td style="text-align:right;">' . $abc . '</td></tr>';
}
echo $output;`

Example of A Generated serialized String

a:3:{i:0;s:177:"66 - عدم تخزين وحفظ المواد الغذائية الجافة والمبردة والمجمدة في درجة مناسبة حرارة مناسبة لكل نوع";i:1;s:76:"13 - عدم وجود لوحة إعلانية بالاسم التجاري";i:2;s:63:"9 - إضافة فرع أو مستودع بدون ترخيص";}

Above String in Unserialized Format

66 - عدم تخزين وحفظ المواد الغذائية الجافة والمبردة والمجمدة في درجة مناسبة حرارة مناسبة لكل نوع,

13 - عدم وجود لوحة إعلانية بالاسم التجاري,

9 - إضافة فرع أو مستودع بدون ترخيص


Solution

  • If I understand correctly now, the problem is that it keeps adding the output of previous $row contents into your output when it processes subsequent rows, resulting in a problem like we see in this live demo: https://3v4l.org/eXXRX.

    If so, that is because $abc is not reset each time the outer foreach is executed. You can easily fix that by moving $abc=''; inside that loop:

    foreach($result as $row)
    {
      $abc='';
      $fine_types = unserialize($row['fine_type']);
      
      echo "<td>";
      foreach ($fine_types as $fine_type) {
        $abc .="<div dir='rtl' lang='ar' class='fntype'> ".$fine_type.'</div>';
      }
      echo "</td>";
    
      $output .= '
        <tr>
                <td style="text-align:right;">' . $abc . '</td></tr>';
    }
    echo $output;
    

    Demo with correction: https://3v4l.org/vCQ5V