开发者

Combine arrays PHP

开发者 https://www.devze.com 2023-01-10 09:00 出处:网络
I have tree arrays like this $keys = array("elment1","elment1","elment2","elment1");

I have tree arrays like this

$keys = array("elment1","elment1","elment2","elment1");
// This one can have duplicates values
$operator = array("=","<",">","=");
// Operators for MySql query 
$queries = array("query1","query2","query3","query4");
// This one can have mixed values

I want to know how to combine this tree arrays to have a query like this:

$string = "SELECT FROM tables
           WHERE
           (elment1 = query1 OR elment1<query2 OR elment1=query4)
           // For the group of duplicates keys
           AND
           elment2 > query3";
           // For the non duplicates

I need this for multi-filter queries.

The user should push a button to add keys, operator and query as many times as he like.

I'm using jquery to create form elements, and e开发者_运维知识库ach() function to generate 3 arrays, before posting all to php.


You asked a question in French, I'll answer in English and you can use Google Translate if you need a translation. [Utilisez Google Translate pour traduire cette réponse si vous voulez.]

First of all, you'll need to concatenate the pieces. Pay attention to the mysql_real_escape_string, which makes the whole operation a little bit safer.

$joined = array();
for($i = 0, $size = sizeof($keys); $i < $size; ++$i) {
    $joined[$i] = $keys[$i] . " " . $operator[$i] . " '" . mysql_real_escape_string($queries[$i]) . "'";
}

Then you can use implode:

$string = 'SELECT [...] WHERE (' . implode(' OR ', $joined) . ')';


Bonjour,

Here is the code. tried and tested. Voila le code... essayer avec succé

$keys = array("elment1","elment1","elment2","elment1");
// this one can have duplicates values , 
$operator = array("=","<",">","=");
// operators for Mysql query 
$queries = array("query1","query2","query3","query4");
// mixtes values

$joined = array();
for($i = 0, $size = sizeof($keys); $i < $size; ++$i)
{
    $joined[$keys[$i]][] = $keys[$i] . $operator[$i] . $queries[$i];
}

foreach ($joined as $key => &$value)
{
    $value = implode(' OR ', $value);
    $value = "(" . $value . ")";
}
$query = implode(' AND ', $joined);
print $query;
0

精彩评论

暂无评论...
验证码 换一张
取 消