简体   繁体   中英

How to search through Json by keyword in PHP?

i am currently having problem with searching through json file, and i am searching and showing faculties based on searched word but it only shows the value when i type in the full name, how can i get search to work if i like only type first few characters and show the results with name starting with it.

here is my code:

<?php
if(isset($_GET['search_word']))
{
$search_word=$_GET['search_word'];
$string = file_get_contents("faculty_info.json");
$jfo = json_decode($string);
// copy the posts array to a php var
$posts = $jfo->faculty_info;
// listing posts
foreach ($posts as $post) {
    if($post->name == "$search_word"){
    echo $post->name;
    echo "<br>";
    echo $post->division;
    echo "<br>";
    echo $post->school;
    echo "<br>";
    echo $post->designation;
    echo "<br>";
    echo $post->email;
    echo "<br>";
    echo $post->room;
    echo "<br>";
    echo "<br>";
    }
}
}
?>

Try this

$post->name = 'How are you?';
$search_word = "How";

$pos = strpos($post->name, $search_word);

if ( $pos !== false && $pos == 0) {
   echo 'found';
   //do your script
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM