user3312802 user3312802 - 1 month ago 6
PHP Question

Search from multidimensional array

This is the

array
where I want to search

$contacts =array(
array( "name"=>"Samatha Perera", "Email"=>"smatha@gmail.com", "Telephone"=>array("office"=>"0112233789","personal"=>"0718256385","home"=>"0112843425")),
array( "name"=>"Charith Fernando", "Email"=>"charith@gmail.com", "Telephone"=>array("office"=>"0112656457","personal"=>"0718456723","home"=>"0112334466")),
array( "name"=>"Malith Wijekoon", "Email"=>"malith@hotmail.com", "Telephone"=>array("office"=>"0332301311","personal"=>"077456453","home"=>"0112556677")),
array( "name"=>"Sanath Perera", "Email"=>"sanath@yahoo.com", "Telephone"=>array("office"=>"0112201654","personal"=>"0757277365","home"=>"0312867725")),
array( "name"=>"Gihan Indran", "Email"=>"gihan@gmail.com", "Telephone"=>array("office"=>"032222526","personal"=>"0778856385","home"=>"0322243426")),
);


Form will look like this

Search By : Name or Email or Telephone (This is a combo box)

Search Value : _______________ (Search Button)

I want to search and display the results in table as follows.

-----------------------------------
Name | Email | Telephone


Samatha Perera smatha@gmail.com Office:0112233789

Personal:0718256385

Home:0112843425

Answer

Try this.... bellow code will match any text....

//$search = 'Samatha';
//$search = '011';
$search = 'Ferna';

$match = array();
?>
<table>
<tr>
<td>Name</td>
<td>Email</td>
<td>Phone</td>
</tr>
<?php
foreach($contacts as $key => $value) {

    if(strpos($value['name'],$search) !== false || strpos($value['Email'],$search) !== false) {
        $match[] = $value;
        continue;
    }

    foreach($value['Telephone'] as $k => $v) {
        if(strpos($v,$search) !== false) {
            $match[] = $value;
            break;
        }
    }


}
if(!empty($match))
foreach($match as $key => $value) {
    ?>

<tr>
<td><?php echo $value['name']?></td>
<td><?php echo $value['Email']?></td>
<td><?php 
foreach($value['Telephone'] as $k => $v) {
    echo "{$k} : {$v}<br />";
}
?></td>
</tr>
    <?php
}
?></table>
Comments