假设我在一个处理查询的php文件中有很多连接和子查询的查询。 Nb:我在底部提供了$ query的示例
$query = query here;
if ($query) {
return $query->result();
} else {
return false;
}
}
然后在我处理html的php文件中,我有一些常用的foreach循环,其中包含一些需要进行其他查询的条件,例如; 注意:结果包含对象$ query-> result()。
foreach ($results as $item) {
$some_array = array();
$some_id = $item->id;
if ($some_id != 0) {
//id_return_other_id is a function that querys a db table and returns the specified column in the same table, it returns just one field
$other_id = id_return_other_id($some_id);
$some_query = another query that requires some joins and a subquery;
$some_array = the values that are returned from some_query in an array
//here i'm converting obj post into an array so i can merge the data in $some_array to item(Which was converted into an array) then convert all of it back into an object
$item = (object)array_merge($some_array, (array)$item);
}
//do the usual dynamic html stuff here.
}
这很好用但是因为我不喜欢我在循环中做很多查询的方式,有没有办法在处理查询的文件中添加if $ some_id!= 0? 我试过了
$query = query here;
//declaring some array as empty when some_id is 0
$some_array = array();
if ($query) {
if ($some_id != 0) {
//same as i said before
$other_id = $this->id_return_other_id($some_id);
$some_query = some query;
$some_array = array values gotten from some query;
}
$qresult = (object)array_merge($some_array, (array)$query->result);
return $qresult;
} else {
return false;
}
}
由于显而易见的原因,这不起作用,是否有任何想法?
此外,如果有一种方法可以在$ query中创建这些条件和查询,我会永远爱你。
Ps:演示查询类似于
$sql = "SELECT p.*,up.*,upi.someField,etc..
FROM (
SELECT (another subquery)
FROM table1
WHERE table1_id = 3
UNION ALL
SELECT $user_id
) uf
JOIN table2 p
ON p.id = uf.user_id
LEFT JOIN table3 up
ON .....
LEFT JOIN table4
ON ....
LEFT JOIN table5
ON ....
And so on..etc..
ORDER BY p.date DESC";
$query = mysql_query..
答案 0 :(得分:2)
您似乎只需要在查询文件中运行两个查询。第一个查询将获得您正在寻找的广泛内容。第二个查询将查询结果中的id并执行新查询以获取有关该特定id的任何详细信息。我在我的应用程序的客户搜索页面中使用了类似的东西。
$output = array();
$query1 = $this->db->query("SELECT * FROM...WHERE id = ...");
foreach ($query->result_array() as $row1)
{
$output[$row1['some_id']] = $row1;
$query2 = $this->db->query("SELECT * FROM table WHERE id = {$row1['some_id']}");
foreach ($query2->result_array() as $row2)
{
$output[$row1['some_id']]['data_details'][$row2['id']] = $row2;
}
}
然后在显示html的页面中,您只需要两个foreach:
foreach($queryresult as $key=> $field)
{
echo $field['some_field'];
foreach($child['data_details'] as $subkey => $subfield)
{
echo $subfield['some_subfield'];
}
}
我知道你正在使用对象,但你可能会将其转换为使用该格式。我希望这有意义/有帮助。
答案 1 :(得分:0)
使用此
if ($some_id !== 0) {
而不是
if ($some_id != 0) {