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?
The query() / mysqli_query() function performs a query against a database.
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.
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.
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
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');
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With