我将https://github.com/Loilo/Fuse用作模糊搜索PHP引擎。
这有效:
<?php
error_reporting(E_ALL);
ini_set('diaplay_errors', 1);
require 'vendor/autoload.php';
$fuse = new \Fuse\Fuse([
[
"title" => "Old Man's War",
"author" => "John Scalzi"
],
[
"title" => "The Lock Artist",
"author" => "Steve Hamilton"
],
[
"title" => "HTML5",
"author" => "Remy Sharp"
],
[
"title" => "Right Ho Jeeves",
"author" => "P.D Woodhouse"
],
], [
"keys" => ["title", "author"],
]);
$query = $_GET['query'];
print_r($fuse->search(".$query."));
/*
Array
(
[0] => Array
(
[title] => The Lock Artist
[author] => Steve Hamilton
)
[1] => Array
(
[title] => HTML5
[author] => Remy Sharp
)
)
*/
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="get">
<input type="" name="query">
</form>
</body>
</html>
但是当我尝试这样做时:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require 'config.php';
$query = $_GET['q'];
if ($query == null) {
exit('No query');
}
$sql = "SELECT title,uploader FROM `uploads_public` ";
if ($stmt = $pdo->prepare($sql)) {
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":query", $query, PDO::PARAM_STR);
// Attempt to execute the prepared statement
if ($stmt->execute()) {
echo "Your search $query has the following results(normal json):<br>";
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results, JSON_PRETTY_PRINT);
echo ($json) . '<br>';
echo "While it has the following results when replaced<br>";
$stuff = str_replace('}', ']', str_replace(':', '=>', str_replace('{', '[', "$json")));
$json_results = substr($stuff, 1);
echo $json_results . '<br>' . '<br>';
echo "Here are you <b>real</b> search results:<br>";
} else {
echo "Something went wrong. Please try again later. <br>";
print_r($stmt->errorInfo());
}
// Close statement
unset($stmt);
unset($pdo);
} else {
die("no input");
}
require 'vendor/autoload.php';
$fuse = new \Fuse\Fuse($json_results);
print_r($fuse->search(".$query."));
我收到此错误:
Warning: array_values() expects parameter 1 to be array, string given in C:\Bitnami\wampstack-7.0.0RC7-\apache2\htdocs\vendor\loilo\fuse\src\Fuse.php on line 54
$json_results
的语法非常完美,除了它是 string 。这就是问题的开始。 $fuse = new \Fuse\Fuse();
需要关联数组作为其与这样的语法参数为$json_results
。$json_results
是因为需要正确的格式/语法的字符串。
所以我的问题是:我怎么转换$json_result
到一个数组,这样的功能array_values()
可以在其上使用,同时仍保持相同的语法/格式
答案 0 :(得分:0)
您好,我已经检查了您的代码,可以看到它不是字符串,而是它的集合。
尝试使用数组而不是字符串来创建Fuse对象。