0

So I'm doing something wrong (new to PHP) and I think the issue is related to my inexperience with manipulating arrays in php.

    $query2 = "SELECT * FROM birds where breed = '".$row['breed']."' and wing_span = '".$row['wing_span']."' and id != '".$row['id']."' limit 4";
    $s_query = mysql_query($query2);

    $theArray = array();

    $counter = 0;
    while($row3 = mysql_fetch_assoc($s_query)) {
        $counter = $counter + 1;
        array_push($theArray, $row3);
    }

    if($counter < 4) {
        $new_limit = 4 - $counter;

        $query5 = "SELECT * FROM birds where breed = '".$row['breed']."' and id != '".$row['id']."' limit ".$new_limit."";
        $s_query2 = mysql_query($query5);

        $counter = 0;
        while($row5 = mysql_fetch_assoc($s_query2)) {
            $counter = $counter + 1;
            array_push($theArray, $row5);
        }
    }

The goal is that if I don't reach the maximum of 4 in the first query, I will run a second query with the difference in MAX - count as the limit. But when I run that query, I try to add the rows ($s2_query) to the existing rows ($s_query)

In this attempt, I tried to create a new array, push the elements as I go. I've tried manually combining them too (array_merge), but also didn't work.

Edit It's intentional for there to be two queries. Point is that if the first query doesn't give me a total of 4 results, I run a second query to fill the remaining spots.

4

2 回答 2

2

编辑后的答案deceze在我认为应该可以正常工作的评论中建议了一个 UNION,请尝试:

$query = "(SELECT *, 1 as SORY_QUERY1 FROM birds where breed = '".$row['breed']."' and wing_span = '".$row['wing_span']."' and id != '".$row['id']."') UNION (SELECT *, 2 FROM birds where breed = '".$row['breed']."' and id != '".$row['id']."') ORDER BY SORY_QUERY1 LIMIT 0, 4";

$theArray = mysql_fetch_array($s_query);

var_dump($theArray); //to debug

顺便说一句,你可以使用

$theArray[] = $row5;

代替

array_push($theArray, $row5);
于 2012-12-18T22:17:04.807 回答
0

正如 deceze 所说,只有 1 个 UNION 请求最适合您的需求。

顺便说一句,使用限制作为范围

LIMIT 0, 4

问候,

于 2012-12-18T22:39:56.167 回答