[英]Search mysql with wildcard and put results into php array
说我有出场this is the RED color
, this is the BLUE color
, this is WHATEVER color
,他们属于作为不同的句子的部分,在我的MySQL数据库的表表中的列列不同的细胞,或在如果这个表相同的行。
----------------------------------------------------------------------------------------
| column |
----------------------------------------------------------------------------------------
| Look, this is the red color which is is not a nice one. |
----------------------------------------------------------------------------------------
| And this is the blue color, I like it more. |
----------------------------------------------------------------------------------------
我怎么能在数据库中执行搜索,因为this is the % color
完全匹配this is the % color
,并将结果放入PHP数组中,这样我就可以完全像输出数组一样
这是RED的颜色
这是蓝色
这是WATEVER颜色
跳过相应句子的所有其他部分? 我的意思是我需要放入数组只有每一个外观都是CURRENT_WILDCARD_VALUE颜色而已。
到目前为止,我有以下PHP代码
global $wpdb;
$query = $wpdb->get_results( "SELECT * FROM table WHERE row LIKE '% this is the % color %'");
print_r($query);
它返回大量的额外数据,而我需要它只返回我的搜索词,记住它使用的通配符。
从MySQL中选择了值后。 通过preg_match()传递每个记录值。 大致如下的东西:
$myValue = 'Look, this is the red color which is is not a nice one.'; // Value from MySQL
$matches = array();
preg_match ('/this is the (.+) color/', $myValue, $matches);
$ matches的值应为:
array (
0 => 'this is the red color',
1 => 'red',
)
如果您想保留一组唯一值(例如红色),最简单的方法是将每个$ matches [1]存储为数组键。 例如
$myColors = array(); // Put this before record iterator
$myColors[$matches[1]] = $matches[0];
这会产生一个数组:
array (
'red' => 'this is the red color',
'blue' => 'this is the blue color',
)
最后,我最终得到了以下代码,似乎符合我的期望:
global $wpdb;
// setting up the database search term
$srchtrm = "green";
// querying WP database for matches and putting their parent cells into array
$query = $wpdb->get_results("
SELECT post_content
FROM wp_posts
WHERE post_content
REGEXP 'This is the $srchtrm color'
");
// simplifying the query resulting array
foreach ($query as $value) {$simplified_array[] = $value->post_content;}
// avoiding php's Warning: implode(): Invalid arguments passed in
if (empty($simplified_array)) {}
// converting the simplified array into a single text string
else {$textstring = implode(" ", $simplified_array);}
// searching the above text string for matches and putting them into array
preg_match_all('/This is the '.$srchtrm.' color/', $textstring, $matches);
// removing repeating items in simplified array
$simplifiedmatches = array_unique($matches[0]);
// sorting the simplified matches array asc
sort($simplifiedmatches);
// outputting values
foreach($simplifiedmatches as $match) {echo $match.'<br />';}
我严格设置green
为$srchtrm
在这个例子中值,但$srchtrm
实际上是一个动态的变量,因此一切都很好,我并不想只创建一个关键的数组。
代码是否一切正常,或者可能存在一些隐藏(对我来说)错误?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.