php - 无法将关联字符串转换为关联数组
问题描述
我使用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
for 的语法$json_results
很完美,只是它是一个字符串。这就是问题开始的地方。$fuse = new \Fuse\Fuse();
需要一个关联数组作为其参数,其语法为$json_results
. $json_results
是具有所需格式/语法的字符串。
所以我的问题是:如何转换$json_result
为数组,以便array_values()
可以在其上使用该函数,同时仍保持相同的语法/格式?
解决方案
您好,我已经检查了您的代码,我可以看到它不是字符串,而是集合。
尝试使用数组而不是字符串来创建 Fuse 对象。
推荐阅读
- jquery - HTML 元素的视差效果
- hp-uft - 统一功能测试 GitHub 集成
- objective-c - 在 objectAtindex swizzling for NSMutableArray 中使用自动释放池
- python-3.x - 分别部署多个 AWS lambda
- azure-active-directory - Microsoft Graph API - 从 id 列表中获取目录对象 - 错误请求
- android - 使用 webview 时,html 自动重定向代码会起作用吗?
- android - 使用其他域帐户在 google play 开发者控制台中邀请新用户
- java - 不显示 TableView Javafx 的行
- php - 无需设备令牌或注册 ID 即可向 APP 发送推送通知
- php - PHP 表单验证不起作用,允许发送无效提交