我正在尝试使用PHP将名为“books”的表的记录保存到数组中。 book table有一些我想要获取的列。因此我写了这个查询:
"SELECT b.book_name,b.book_description,b.book_link,c.category_name FROM books b,
category c WHERE b.category_id = c.category_id AND b.category_id !=0"
我能够将数据提取并存储到数组中,但是当我将数组作为JSON响应打印时,您会发现问题。
{"book_name":"Book 1","0":"Book 1","book_description":"this is the book number 1","1":"this is the book number 1","book_link":null,"2":null,"category_name":"Story","3":"Story"}
我的问题,如何从数组中删除这些重复的项目(“0”:“Book 1”)?
完整的PHP代码:
<?php
include("connection.php");
getAllBooks($cnn);
//Print result as json
function getAllBooks($cnn)
{
$query = "SELECT b.book_name,b.book_description,b.book_link,c.category_name FROM books b,
category c WHERE b.category_id = c.category_id AND b.category_id !=0";
$stmt = $cnn->prepare($query);
$stmt->execute();
$rowcount = $stmt->rowCount();
$myObj = new stdClass();
if($stmt->rowCount() > 0)
{
$books_list = array();
while($row= $stmt->fetch())
{
$myObj2 = $row;
$books_list[] = $row;
}
$myObj -> action_result ="success";
$myObj -> books_list =$books_list;
}
else
{
$myObj -> action_result ="fail";
}
$jsonObj = json_encode($myObj);
echo $jsonObj;
}
?>
答案 0 :(得分:0)
您要么传递PDO::ATTR_DEFAULT_FETCH_MODE
,默认值为PDO::FETCH_BOTH
(默认为while($row = $stmt->fetch(PDO::FETCH_ASSOC))
)。
PDO :: FETCH_BOTH(默认值):返回由结果集中返回的列名和0索引列号索引的数组。
$stmt->setFetchMode(PDO::FETCH_ASSOC);
或者在获取之前设置它:
public class Person
{
[Required]
public string SpecialSauce { get; set; }
[Required]
public string Name { get; set; }
}