简体   繁体   中英

Php using Foreach and obtain a single result

I've a table in mysql where I find some values and put them in an array.

Assume that the value of the array are 1 and 5

Now I use this array for a query in another table where I have 5 id and I'd like that it shows me all the id minus the ones of the array (so only 2,3,4)

This is the code I use to pass the foreach in a query

foreach ($array as $value) {
    $arr=array();   

    $query= "SELECT * FROM test WHERE data NOT LIKE '%$value%'";
    $result=mysqli_query($con,$query);

    while($row = mysqli_fetch_array($result)) {
        echo $row["id"];
    }
}

The result I'd like to obtain is "2,3,4" but it gives to me 2,3,4,5,1,2,3,4

This is the array creation

$array= array();
$query= "SELECT * FROM test WHERE time1>= '$startTime' AND time1 <=    '$endTime'";
$result=mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)) {
$array[]=$row["data"];
}

How can do?

Why not do a better SQL query?

$query= "SELECT * FROM test WHERE data NOT IN (".implode(',',$array).")";

Or translating:

SELECT * FROM test WHERE data NOT IN (1,5)

Change to $query= "SELECT * FROM test WHERE data NOT LIKE '%$value%' AND id NOT IN ({implode(',',$array_of_ids_you_dont_want)})"; ?

Edit:

I have added an 'id' key to your first array and moved the 'data' field to 'data' key.

$array= array();
$query= "SELECT * FROM test WHERE time1>= '$startTime' AND time1 <=    '$endTime'";
$result=mysqli_query($con,$query);
while($row = mysqli_fetch_array($result)) {
    $array[]= array(
        'id'=>$row['id'],
        'data'=>$row["data"]
    );
}

Having the id available you can than use array_map function to get a new array of all ids. You can then use this array to construct the where condition. It is wise you use that before the foreach because it will be same for each iteration. Finally now that $array contains sub arrays, when foreaching the element will be the array with id and data keys from above.

$exclude_ids = array_map(function($el){return $el['id'];},$array);
$exclude_ids_query = "id NOT IN ({implode(',',$exclude_ids)})";

foreach ($array as $element) {
    $arr=array();   
    $query= "SELECT * FROM test WHERE data NOT LIKE '%{$element['data']}%'".$exclude_ids_query;
    $result=mysqli_query($con,$query);

    while($row = mysqli_fetch_array($result)) {
        echo $row["id"];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM