如何根据需要格式化PHP中的数组?

时间:2019-03-13 16:26:32

标签: php mysql sql

我有一个简单的目标数据库

$sql=mysqli_query($con,"SELECT * FROM users,rating WHERE users.user_id=rating.user_id GROUP BY rating.user_id");

$output=array();
while($hsl=mysqli_fetch_array($sql)){

$str=$hsl['username'];

$sql1=mysqli_query($con,"SELECT * FROM destination,rating WHERE rating.dest_id=destination.dest_id AND rating.user_id='$hsl[user_id]'");

while($hsl1=mysqli_fetch_array($sql1)){
$user_id=$hsl1['user_id'];
$title=$hsl1['title'];
$rating1=$hsl1['1_rating'];
$rating2=$hsl1['2_rating'];
$rating3=$hsl1['3_rating'];
$rating4=$hsl1['4_rating'];
$avg=($rating1+$rating2+$rating3+$rating4) / 4;
$str1=$title;
$str2=$avg;

如何格式化数组以获取每个用户的结果,如下所示?

$rekom =  array(
"user1" => array("Monumen Nasional" => 3.25, 
              "Kota Tua" => 3,
                "Tidung Island" => 2),

"user2" => array("Monumen Nasional" => 3.5, "Kota Tua" => 4.25,
                  "Tidung Island" => 2),

"user3" => array("Monumen Nasional" => 2.25, "Kota Tua" => 4.5,
                "Tidung Island" => 3.75),

"user4" => array("Monumen Nasional" => 2, "Kota Tua" => 4, "Tidung Island" => 4),

"user5" => array("Monumen Nasional" => 4.25, "Tidung Island" => 4)    

);

我已经尝试过此代码,但无法解析所有用户:

$rekom = array($str => array($title => $str2));

1 个答案:

答案 0 :(得分:1)

您可以使用joins来获取所需的所有信息,因此您可以使用一个查询,而不是数据库中1 +个用户。如果您有很多用户,则可以带来巨大的性能优势。

下面,我假设您将目标名称保存在title列中,并且这些值'user1','user2'...存储在user_id列中。如果列名不同,请随时更改我的代码。

$sql = "SELECT * FROM users 
        INNER JOIN rating ON users.user_id=rating.user_id
        INNER JOIN destination ON rating.dest_id = destination.dest_id";


$result = mysqli_query($con, $sql);

$reviews = [];

while($row = mysqli_fetch_array($result)) {

    $rating = ($row['1_rating'] + $row['2_rating'] + $row['3_rating'] + $row['4_rating']) / 4;
    $reviews[$row['user_id']][$row['title']] = $rating;
}

print_r($reviews);

这将为您提供所有获得用户评论的目的地。

修改 您可以通过在AVG(1_rating + 2_rating + 3_rating + 4_rating)中添加SELECT来计算平均值。另外,您还应该添加group by dest_id, user_id