Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: What is the best method to SQL query an array? (if you can)

Tags:

arrays

php

mysql

Consider this:

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

One array that has the same data.

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

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.

Is there a shortcut here?

like image 217
Talvi Watia Avatar asked Aug 21 '10 21:08

Talvi Watia


People also ask

Which is the correct function to execute the SQL queries in PHP?

The query() / mysqli_query() function performs a query against a database.

What are the 3 types of PHP arrays?

In PHP, there are three types of arrays: Indexed arrays - Arrays with a numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.

Can we use array in SQL query?

The ARRAY function returns an ARRAY with one element for each row in a subquery. If subquery produces a SQL table, the table must have exactly one column. Each element in the output ARRAY is the value of the single column of a row in the table.


2 Answers

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');

or if you are using PHP >= 5.3.0

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

See it in action on ideone


EDIT:

You can also try 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'); 
like image 50
NullUserException Avatar answered Sep 29 '22 21:09

NullUserException


CakePHP has a Set::extract method that uses XPath query strings to find information. It's quite good and I think it shouldn't be too hard to use it without the rest of the CakePHP project.

like image 38
pr1001 Avatar answered Sep 29 '22 20:09

pr1001