如何在PHP中通过关键字搜索Json?

时间:2016-02-12 17:42:59

标签: php json

我目前在搜索json文件时遇到问题,我正在搜索并显示基于搜索到的单词的功能,但它只显示我输入全名时的值,如果我只喜欢,我怎样才能获得搜索功能输入前几个字符,并以名称开头显示结果。

这是我的代码:

<?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>";
    }
}
}
?>

1 个答案:

答案 0 :(得分:0)

试试这个

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

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

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