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

Consider this:

One mySQL database that has tables, rows, and data.

One array that has the same data.

Now, as a rule, I will have such a query for mySQL SELECT * FROM 'table' WHERE name LIKE '%abc%'

But I want to execute the same query in an array without inserting it. The only method that comes to mind is to use array_search , but the syntax is different and the method is confusing.

Is there a shortcut here?

+3
source share
4 answers

You cannot use SQL with arrays, but one way you could make your example is to use array_filter():

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

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

or if you use PHP> = 5.3.0

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

ideone


EDIT:

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

sql4array, SQL PHP, , . , , SQL.

, , PHPLinq

array_filter()

+1

. SQL. , , , , array_search . , , preg_match.

$data = array(
  array('name' => 'foo abc bar', 'lorem' => 'ipsum'),
  array('name' => 'etc', 'lorem' => 'dolor')
);
$matches = array();
foreach ($data as $row) {
  if (preg_match('/^.*abc.*$/', $row['name']) {
    $matches[] = $row;
  }
}
0

CakePHP has Set :: extract , which uses XPath query strings to find information. This is not bad, and I think it should not be too difficult to use without the rest of the CakePHP project.

0
source

Source: https://habr.com/ru/post/1760924/


All Articles