删除php数组

时间:2016-08-23 11:25:45

标签: php arrays

我编写了一个代码来解析php中的数据,如下所示:

<?php
$db_name="hotels";
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass,$db_name);


if(! $conn ) {
    die('Could not connect: ' . mysqli_error());
} 
else{
    //echo"<h3>Database cannection established</h3>";
}

$sql_query_for_username = "select distinct `username` from hotels.ratingoffooditem";
$usernames_result = mysqli_query($conn, $sql_query_for_username);

$users = array();
while($row=mysqli_fetch_array($usernames_result)){
    array_push($users, $row["username"]);
}

//print_r($users);
$response=array();
foreach($users as $user){
    $sql_query= "select `food item`,rating from hotels.ratingoffooditem where username='$user'";

    $result= mysqli_query($conn,$sql_query);
    $abc = array();
    if($result !=false){
        while($row=mysqli_fetch_array($result)){
            $def = array($row["food item"]=>$row['rating']);
            //echo (json_encode($def));
            //echo "</br>";
            array_push($abc,$def);

        }

   }
      //echo "</br>";
            //print_r(json_encode($abc));
            //echo "</br>";
        array_push($response, array("$user"=>array($abc))); 
   //echo "</br>";
}

echo json_encode($response);
//echo "</br>";echo "</br>";echo "</br>";

mysqli_close($conn);
?>

我想获得如下结果:

{&#34;什里&#34; {&#34;希肯-莫莫&#34:4,&#34;巴夫-莫莫&#34;:3,&#34;鸡-Thukpa&#34; :3,&#34; Chiken Momo&#34;:4,&#34; Buff Chowmein&#34;:2.5,&#34; Veg-Chowmein&#34;:3.5},&#34; Juppi&#34;: {&#34;咖喱角&#34;:4},&#34;律&#34; {&#34;希肯-莫莫&#34;:1},&#34; bidur&#34; {&#34 ;希肯-莫莫&#34;:4.5}}

但是,我得到了这个:

[{&#34;什里&#34;:[[{&#34;比萨&#34;:&#34; 3&#34;},{&#34;汉堡&#34;:&#34; 3.5&#34;},{&#34; Chiken-Momo&#34;:&#34; 4.5&#34;},{&#34; Chiken Momo&#34;:&#34; 4&#34;} ,{&#34; Chiken Momo&#34;:&#34; 4&#34;},{&#34; Chiken-Momo&#34;:&#34; 4&#34;},{&#34; Veg -Chowmien&#34;:&#34; 2&#34;},{&#34;巴夫-莫莫&#34;:&#34; 3&#34;},{&#34;希肯-Thukpa&#34 ;: &#34; 4&#34;},{&#34;希肯-Thukpa&#34;:&#34; 4&#34;},{&#34;希肯-Thukpa&#34;:&#34; 2&# 34;}]]},{&#34; Juppi&#34;:[[{&#34;咖喱角&#34;:&#34; 4&#34;},{&#34;希肯-莫莫&#34; :&#34; 4&#34;}]]},{&#34;律&#34;:[[{&#34;希肯-莫莫&#34;:&#34; 1&#34;}]]} ,{&#34; bnabin51&#34;:[[{&#34;希肯-莫莫&#34;:&#34; 4.5&#34;}]]},{&#34; bidur&#34;:[ [{&#34;希肯-莫莫&#34;:&#34; 4.5&#34;}]]}]

现在我该如何删除不必要的括号?

1 个答案:

答案 0 :(得分:1)

最后,我得到的内容如下:

$response=array();
foreach($users as $user){
    $sql_query= "select `food item`,rating from hotels.ratingoffooditem where username='$user'";

    $result= mysqli_query($conn,$sql_query);
    $abc = array();
    if($result !=false){
        while($row=mysqli_fetch_array($result)){
            $abc[$row['food item']]=$row['rating'];

        }

    }

    $response[$user]=$abc;

}