首页 > 解决方案 > 无法将关联字符串转换为关联数组

问题描述

我使用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()可以在其上使用该函数,同时仍保持相同的语法/格式?

标签: phparrayssearchassociative-array

解决方案


您好,我已经检查了您的代码,我可以看到它不是字符串,而是集合。

尝试使用数组而不是字符串来创建 Fuse 对象。


推荐阅读