如何格式化关联数组

时间:2019-02-01 19:39:16

标签: php arrays format associative-array

我有此代码:

enum SomeSerializer {
    Whatever(Box<dyn erased_serde::Serializer>),
}

从根本上讲,它是要获取mysql数据并将其转换为 这样的内容(即这种语法):

<?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 PDO:FETCH_ASSOC):<br>";
               $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
               print_r($results);


              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(($results+= ["keys" => "title"]));
echo("var_dump returns:<br>");

print_r($results);
print_r($fuse->search(".$query."));

但是它输出:

[list] => Array
        (
            [0] => Array
                (
                    [title] => Old Man's War
                    [author] => John Scalzi
                )

            [1] => Array
                (
                    [title] => The Lock Artist
                    [author] => Steve Hamilton
                )

            [2] => Array
                (
                    [title] => HTML5
                    [author] => Remy Sharp
                )

            [3] => Array
                (
                    [title] => Right Ho Jeeves
                    [author] => P.D Woodhouse
                )

        )

)

我需要添加什么额外的代码以使其按自己的方式格式化? ................................................... ................................................... ................................................... ................................................... .................................

1 个答案:

答案 0 :(得分:0)

如果author实际上是uploader,则将查询更改为别名:

SELECT title, uploader AS author FROM `uploads_public`

如果它是实际列,则:

SELECT title, author FROM `uploads_public`

第二,获取list数组:

$results['list'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
除非您可以解释它应该做什么,否则

$results+= ["keys" => "title"]是一个谜。可能只使用$results