18 November 2009

how to use explode function in php

Here is the example to use explode function on an array fetched from database values separated by comma ( , ) and count duplicate values also.
  1. First create database " your database" and a table named "blog".
  2. Enter some data a:-
  3. For first row- insert following data---   Ankit, Om
  4. For second row- insert following data---   Ankit, Ajeet, Santosh.
  5. After that create a php page and paste following coding and change username, password and database name.

<table cellpadding="0" cellspacing="0" class="backcolor" style="border: 1px solid rgb(204, 204, 204);">
<?php
mysql_connect('localhost','Username','Password');
mysql_select_db('database_name');
$sql = "select tag from blog";
$result = mysql_query($sql)or die('Error in get blog detail'.mysql_error());
$toTagArray = array();
$i=0;
while($tag = mysql_fetch_row($result)){
  $TagArray = explode(",", $tag[0]);
  $toTagArray = array_merge($toTagArray,$TagArray);
  $i += 1;
}
$new_array = array_count_values($toTagArray);
ksort($new_array);
while (list ($key, $val) = each ($new_array)) {
?>
<tr>
  <td style="font-size: 12px; padding-left: 20px;">
    <ul>
      <li><?php echo "$key  ($val) <br>";?></li>
    </ul>
  </td>
</tr>
<?php }?>               
</table>

The output will be like as:-
Ajeet (1)
Ankit (2)
Om (1)
Santosh (1)

1 comment: