用户有物品。 每个物品都有很多属性(价格,购买日期,条件,名称)
我想返回所有项目及其属性的json数组
这是我的代码:
$user_id = $_GET['user_id'];
$query_user_items = "SELECT product_id FROM user_products WHERE user_id = :user_id";
$item_ids_array = array();
$success = false;
try {
$sth = $connection->prepare($query_user_items);
$sth->execute(array(':user_id' => $user_id));
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
$success = true;
} catch (PDOException $ex) {
$response["success"] = $http_response_server_error;
$response["message"] = $http_message_server_error . " " . $ex;
die(json_encode($response));
$connection = null;
}
if ($success) {
foreach($result as $key=>$value){
$query_get_item_details = "SELECT * FROM products WHERE product_id = :product_id";
$sth = $connection->prepare($qerty_get_item_details);
$sth->execute(array(':product_id'=> $value));
$record = $sth->fetch(PDO::FETCH_ASSOC);
$item_id = $record['product_id'];
$item_name = $record['product_name'];
$item_time_added = $record['product_time_added'];
$item_description = $record['product_description'];
$item_brand = $record['product_brand'];
$item_price_aquired = $record['product_price_aquired'];
$item_bought_from_place = $record['product_bought_from_place'];
}
/*
$response["success"] = $http_response_success;
$response["item_ids_array"] = $new_array;
echo json_encode($response);
我对php不是很好,我不知道在第二次迭代会发生什么(我不知道我是否也正在迭代)
我想$ item_name将被第二项的名称覆盖,然后是第三项,最后我将只有一个对象?如何创建一个对象及其信息数组,然后json_encode呢?
另外,我应该在foreach之外声明这些变量吗?
答案 0 :(得分:2)
您的代码可以缩短如下(这样,您不使用任何循环):
$query = "SELECT p.* FROM user_products u LEFT JOIN products p ON (p.product_id = u.product_id) WHERE u.user_id = :user_id";
try
{
$sth = $connection->prepare($query);
$sth->execute(array(':user_id' => $_GET['user_id']));
$response = $sth->fetchAll(PDO::FETCH_ASSOC);
}
catch (PDOException $ex)
{
$response["success"] = $http_response_server_error;
$response["message"] = $http_message_server_error . " " . $ex;
}
finally
{
$connection = null;
echo json_encode($response);
}
然后,在您的ajax成功处理程序中,您可以检查是否设置了成功或消息(如果是这种情况,则会发生错误)。否则,它是一个结果数组,你将遍历它
答案 1 :(得分:1)
您不希望每次迭代都运行新查询。 您可能希望使用单个查询来获取所有数据:
SELECT p.*
FROM user_products AS up
LEFT JOIN products AS p ON p.product_id = up.product_id
WHERE up.user_id = :user_id
在PHP中,您可以将数据收集到数组:
<?php
$data = array();
while($result = $sth->fetch(PDO::FETCH_ASSOC)){
$data[] = $result;
}
?><?=json_encode($data)?>