PHP:SQL 查询数组的最佳方法是什么?(如果可以的话) [英] PHP: What is the best method to SQL query an array? (if you can)

查看:40
本文介绍了PHP:SQL 查询数组的最佳方法是什么?(如果可以的话)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一下:

一个包含表、行和数据的 mySQL 数据库.

One mySQL database that has tables and rows and data within it.

一个具有相同数据的数组.

One array that has the same data.

现在通常,我会对 mySQL 进行这样的查询 SELECT * FROM 'table' WHERE name LIKE '%abc%'

Now normally, I would have a query like this for mySQL SELECT * FROM 'table' WHERE name LIKE '%abc%'

但我想对数组执行相同的查询,而不必插入它.想到的唯一方法是使用 array_search,但语法是不同,方法也很复杂.

But I want to perform that same query on the array, without having to insert it yet. The only method that comes to mind is using array_search, but the syntax is different and the method is convoluted.

这里有捷径吗?

推荐答案

您不能将 SQL 与数组一起使用,但是您可以使用 array_filter() 来完成示例的一种方法:

You can't use SQL with arrays, but one way you could do your example is using array_filter():

function like_abc($v) {
    return strstr($v['name'], 'abc') !== false;
}

$filtered = array_filter($yourArray, 'like_abc');

或者如果您使用的是 PHP >= 5.3.0

or if you are using PHP >= 5.3.0

$filtered = array_filter($yourArray, 
    function($v) { return strstr($v['name'], 'abc') !== false;});

ideone

你也可以试试PHPLinq:

// UNTESTED CODE!
$yourArray = array (
    array('name' => 'abcd', 'age' => 20),
    array('name' => 'dacb', 'age' => 45),
    array('name' => 'aadd', 'age' => 32),
    array('name' => 'babc', 'age' => 11),
    array('name' => 'afgb', 'age' => 17),
);

$result = from('$people')->in($yourArray)
            ->where('$people["name"] => strstr($people["name"], "abc") !== false')
            ->select('$people'); 

这篇关于PHP:SQL 查询数组的最佳方法是什么?(如果可以的话)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆