MySQLi附加更多/更深入的结果

时间:2016-01-02 14:53:34

标签: php mysql json mysqli

我正在努力解决这个问题,这可能是因为我没有使用正确的术语。如果有人能指出我正确的方向,那将是惊人的。我将使用一个假设的情况来简化事情:

我有一个包含两个表的数据库: tableA包含房屋销售记录(房屋ID,地址,价格,当前所有者ID等) tableB包含已经显示房屋的房地产经纪人的记录(房屋ID,房地产经纪人ID,时间和日期,笔记等)。

我希望有一个查询可以搜索当前的所有者ID,并将所有房屋的信息都显示给所有展示房屋的人。我想要检索的是一个JSON数组,它将每个tableB记录的信息附加/附加/添加到tableA的单个记录中。

例如,如果我搜索ownerX拥有的房屋(谁拥有两栋房屋),我希望它返回两个主要项目,其中包含tableB中每个相关条目的子项目。在下面的示例中,ownerX有两个房子。 1234 Fake St的第一栋房子有2个不同的房地产经纪人,总共有3次访问。 555 Nowhere St的第二所房子有两次房地产经纪人访问。

以下是我要检索信息的方式:

tableA - Result 1 (House at address 1234 Fake St)
       tableB - Result 1 (Realtor ID 1234, etc)
       tableB - Result 2 (Realtor ID 1234, etc)
       tableB - Result 3 (Realtor ID 2222, etc)

tableA - Result 2 (House at address 555 Nowhere St)
       tableB - Result 1 (Realtor ID 1111, etc)
       tableB - Result 2 (Realtor ID 1111, etc)

相反,我得到的是:

tableA - Result 1 (House at address 1234 Fake St),tableB(Realtor ID 1234, etc)
tableA - Result 2 (House at address 1234 Fake St),tableB(Realtor ID 1234, etc)
tableA - Result 3 (House at address 1234 Fake St),tableB(Realtor ID 2222, etc)
tableA - Result 4 (House at address 555 Nowhere St),tableB(Realtor ID 2222, etc)
tableA - Result 5 (House at address 555 Nowhere St),tableB(Realtor ID 2222, etc)

我不想每次都检索tableA信息。我只需要一次,然后是tableB的每个子结果。这很重要,因为我将数据返回到创建新列表的应用程序。我目前正在使用mysqli_multi_query

$sql = "SELECT * FROM tableA WHERE ownerID = "ownerX";";
$sql. = "SELECT tableB.*, tableA.houseID FROM tableB,tableA WHERE tableB.houseID = tableA.houseID;";

同样,实际内容只是一个假设。我正在寻找更多的,“你是一个白痴,你应该使用_____”而不是,“你拼错的房地产经纪人,这可能导致问题。”。

此外,请注意,我不是要求使用破折号和括号格式化结果,因为它们在上面。我只是简单地写它,所以它更容易理解。我正在寻找一种在JSON数组中拥有子对象的方法。

非常感谢任何指导我正确方向的帮助!感谢无论谁花时间去刺伤这个! 贝

其他信息: 这是我用来运行查询的代码:

$sql = "SELECT * FROM clocks WHERE user_key='".$userkey."';";
$sql .= "SELECT * FROM milestones WHERE (SELECT clock_key FROM clocks WHERE user_key='".$userkey."') = milestones.clock_key";


if (mysqli_multi_query($con,$sql))
{
  do
    {
    if ($result=mysqli_store_result($con)) {
      while ($row=mysqli_fetch_row($result))
        {
          $myArray[] = $row;
        }
        echo json_encode($myArray); 
      mysqli_free_result($result);
      }
    }
while(mysqli_more_results($con) && mysqli_next_result($con));
}

更新答案:

感谢下面@vmachan的帖子,我最终得到了所有的数据,然后通过一些循环来调整数组。我将使用上面的house / relator示例。

我用他的代码来获取我的结果($ house_id是一个变量输入id):

$sql = "SELECT * FROM tableA INNER JOIN tableB ON tableA.houseID = tableB.houseID WHERE tableA.houseID='".$house_id."';";

我得到了一个包含5个项目的数组,因为tableB有5个条目。由于tableA中只有2个房屋条目,因此它看起来像这样:

["houseID"=>"1","price"=>"50000", "owner" => "Mike G", "state"=>"CA", "realtor" => "Jane D", "visitDay"=>"Tuesday", "notes" => "They liked the house"],
["houseID"=>"1","price"=>"50000", "owner" => "Mike G", "state"=>"CA", "realtor" => "Jane D", "visitDay"=>"Wednesday", "notes" => "They loved the house"],
["houseID"=>"1","price"=>"50000", "owner" => "Mike G", "state"=>"CA", "realtor" => "Stephanie W", "visitDay"=>"Friday", "notes" => "They didn't like the house"],
["houseID"=>"2","price"=>"65000", "owner" => "Michelle K", "state"=>"AL", "realtor" => "Mark S", "visitDay"=>"Tuesday", "notes" => "They made an offer"],
["houseID"=>"2","price"=>"65000", "owner" => "Michelle K", "state"=>"AL", "realtor" => "Jim L", "visitDay"=>"Monday", "notes" => "They stole stuff"]

前三个元素来自tableA,不会改变。所以,我使用循环来基本检查houseID,如果是新房子,创建一个新的房子数组项,否则,将tableB中的细节添加到当前房屋元素:

<?php
//$house is an array will hold all of our indiviaul houses and their infomation.
$houseArray = array();

//Start the foreach loop 
foreach($items as $item){

//$item["houseID"] is the houseID from our database that we got from the above code.
$houseID =$item["houseID"]; 

//$currentID is a varible that is set after the first iteration.
//This checks to see if we're still working with the same house, or a new house.
if($currentID!=$houseID){

//Create an array to hold all of the relator visit information arrays.
//This is created within the loop as it will erased if a new houseID is found in the array.
$relatorVisitArray = array();

//This is a secondary loop that checks the same array. This time, we are only working with the new houseID that from the condition above.
    foreach($items as $rv){

//This cheecks to see if there is a match between the current houseID that we're working with and the other houseIDs in the array. Since we're going through the same array that we're already iterating, it will find itself (which is good).  
    if($houseID==$rv["houseID"]){

//Once is gets a match, it will create a temporary array to hold the "Relator Visit" information. The array is created within the loop as it needs to be cleared through each iteration.    
    $tempRealitorVisit = array(
        'name' => $rv["name"],
        'day' => $rv["day"],    
        'houseID' => $rv["houseID"],
        'notes' => $rv["notes"]
    );

    //At the end of each iteation, we add the temporary to the main $relatorVisitArray. 
    $relatorVisitArray[] = $tempRealitorVisit;
    }
    }

//At this point, the subloop has ended and we're created an array ($relatorVisitArray) which contains all of the $tempRealitorVisit arrays. 
//Remember, were are still within the first loop and have determined that this is a new house.
//Now we'll create a new house array based on the current houseID in this iteration.
//This array is created within the loop because we want it to cear at the next iteation when it's determined that it's a new house.
    $house = array(
       'houseID' => $item["houseID"],
       'owner' => $item["owner"],
       'price' => $item["price"],
       'location' => $item["location"],
       'relatorVisits' => 
       //Here, we simply add the $relatorVisitArray to a key called, "relatorVisits" (ie an array within an array).
            $relatorVisitArray
       );

//We then add the $house to the $houseArray.      
$houseArray[] = $house;

//Finally, we set $currentID to $item["houseID"]. At the next iteration, it will check this id against the next house ID. If they are the same, this entire code will skip until a new houseID appears from your database. 
$currentID= $item["houseID"];

}

  }

   //This prints all of the information so it's easy to read.
    echo '<pre>';
 print_r($houseArray);
    echo '</pre>';
}

?>

最后,我留下了一个包含两个子数组的数组。第一个子阵列(House 1)包含3个子阵列(对该房子的3次访问)。第二个子阵列(House 2)包含2个子阵列(2次访问该房子)。

我希望这可以帮助那些和我有同样问题的人。如果有人知道更清洁的方法,请在这里发布!谢谢你的指导! 贝

2 个答案:

答案 0 :(得分:1)

我认为您可以将如下所示的SQL语句组合在一起来加入clock_key上的时钟和里程碑表,以获取用户提供的值,即$ userkey。然后在您的代码中,您可以循环搜索结果,然后检查连续的house_ids。

library(data.table)
setDT(df1)[, SalesD := round(100*(Sales- 
         Sales[which.min(Year)])/Sales[which.min(Year)]) , Company]
df1
#     ID Company Year  Sales SalesD
# 1:  1     LSL 2015 100000      0
# 2:  2     LSL 2016 120000     20
# 3:  3     LSL 2017 150000     50
# 4:  4     LSL 2018 100000      0
# 5:  5     LSL 2019  50000    -50
# 6:  6     IDA 2015 150000      0
# 7:  7     IDA 2016 180000     20
# 8:  8     IDA 2017 200000     33
# 9:  9     IDA 2018 180000     20
#10: 10     IDA 2019 160000      7

然后,您可以使用与SO posting中的代码类似的代码。您需要更改它,以便在循环内部检查先前的'house_id'是否与当前的'house_id相同,如果没有,您将启动一个新的父数组,否则继续添加到现有数组。在循环结束时,您可以调用encode来获取JSON格式。

希望这有帮助。

答案 1 :(得分:0)

我没有时间实际编写(并测试!)正确的代码,但我建议您将数据收集到两个php关联数组中:$houses以所有者为关键字$visits以houseID为关键。假设一个所有者可以在市场上拥有多个属性,并且知道一个房地产经纪人可以为每个属性支付多个访问权限,那么这两个数组中的条目本身就是数组的数组&#34; s。

样品:

$houses={'ownerx':{'houseID_1':['address_1','price_1'],
                   'houseID_2':['address_2','price_2']}},
         'ownery':{'houseID_3':['address_3','price_3'],
                   'houseID_4':['address_4','price_4']}}
        };  
$visits={'houseID_1':['realtorID_1','realtorID_2', ...],
         'houseID_2':['realtorID_3']
        };

// I used JSON notation for simplicity ...

执行此操作需要您设置一次正确的结构,但这样可以避免您反复查询相同的数据。从关联数组中检索数据也应该非常有效。