【发布时间】:2014-02-08 10:44:38
【问题描述】:
用户有物品。 每件商品都有很多属性(价格、购买日期、状况、名称)
我想返回一个包含所有项目及其属性的 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?p>
另外,我应该在 foreach 之外声明这些变量吗?
【问题讨论】: