PHP/MySql搜索数组与数组 [英] PHP/MySql search array with array
问题描述
我正在建立一个WordPress网站.
I'm building a WordPress website.
使用MySql查询,从数据库中加载所有具有特定品牌的公司:
With a MySql Query I load all companies from my database that have a specific brand:
$results = $wpdb->get_results("SELECT * FROM $wpdb->postmeta WHERE meta_key = 'brand'")`
brand
是一个数组,所以我在数组中搜索特定值:
brand
is an array so I search for a specific value in array:
$brand = $_GET['brand'];
$brandNeedle = $brand;
if(in_array($brandNeedle, $brand[0]))
现在,我的客户要求列出所有与所选公司相关的所有用户.
Now, my client asked to list all users that are connected to all those companies that are selected.
所以我需要创建一个新查询.幸运的是,所有用户都在其列中添加了一个字段,该字段告诉我他们在哪里工作.
So I need to create a new query. Fortunately the users all have a field added to their colum that tells me where they are working.
所以我想:如果我创建一个数组来保存从公司列表中查询的所有公司名称,那该怎么办.
So I thought: what if I create a array that holds all companynames that are queried from the companylist.
通过此数组,我可以选择列中具有公司名称的所有用户
With this array I can select all users who have the company name in their column
所以我认为查询应该是这样的:
So I think the query should be something like this:
SELECT * FROM $wpdb->usermeta WHERE meta_key='company' AND meta_value ='THE ARRAY'
但这并不明显,因为它无法使用数组中的数组进行搜索.
But this doesn't work obvious because it can't search with an array in an array.
我似乎无法弄清楚.有什么想法吗?
I can't seem to figure it out. Any ideas?
-编辑-
好的,所以我执行了爆破功能,但做错了什么:
-- EDIT --
Okay so I did the implode function and I do something wrong:
$brand_array = array();
for($i=0; $i <count($results); $i++){
$result = $results[$i];
if ($i % 2 == 0){
$oddeven = 'even';
}else{
$oddeven = 'odd';
}
$post_id = $result->post_id;
$company_name = get_post_meta($post_id, 'company_name', true);
$brand_array[] = $company_name;
}
print_r($brand_array);
$imploded = implode(',',$brand_array);
$query = "SELECT * FROM $wpdb->usermeta WHERE meta_key='company' AND meta_value IN $imploded";
$persons = $wpdb->get_results($query);
这给了我所需的结果(两个公司组成了一个新的阵列)并给我以下错误:
This gives me the results I need (the two companies in a new array)
and gives me the following error:
WordPress database error: [You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near
'brand1,brand2' at line 1]
SELECT * FROM wp_usermeta WHERE meta_key='company' AND meta_value IN
brand1,brand2
推荐答案
您是否考虑过在MySQL上使用"IN"子句? https://dev.mysql.com/doc/refman/5.0/zh-CN/comparison-operators.html#function_in
Have you thought about using the "IN" clause on MySQL? https://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_in
您可能会遇到类似这样的事情:
You would probably have something like:
$query = "SELECT * FROM ".$wpdb->usermeta." WHERE meta_key='company' AND meta_value IN ('".implode("', ', $brand)."')";
(忘记在中"内容周围添加括号)
(edit: forgot to add the parenthesis around the "in" content)
这篇关于PHP/MySql搜索数组与数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!