How to search an array of associative arrays with multiple required needles and return the indexes?

I am trying to search an array of associative arrays and get the keys of the subarrays that meet all search criteria.

Here is my example:

$list = [
['name' => 'this is items name',
'number' =>  1,
'description' => 'this is description',
'id' => 'just some id',],

 ['name' => 'this is items name2',
'number' =>  1,
'description' => 'this is description2',
'id' => 'just some id',],

 ['name' => 'this is items name3',
'number' =>  1,
'description' => 'this is',
'id' => 'just some id',],
];

I would like to search for "this description" and get the keys of an array like this:

Array ( [0] => 0 [1] => 1 )

I tried this:

$array_key = array_keys(array_column($list, 'description'), 'this description', false);

but it only finds the key if search words exactly match the value. How can I solve this problem?

More precisely, how can I search the whole array not only the column description?

You can use this three cases as starting point:

$list=[
['name' => 'this is items name',
'number' =>  1,
'description' => 'this is description',
'id' => 'just some id',],

 ['name' => 'this is items name2',
'number' =>  1,
'description' => 'this is description2',
'id' => 'just some id',],

 ['name' => 'this is items name3',
'number' =>  1,
'description' => 'this is',
'id' => 'just some id',],
];

$search='this description';
//first type of search : any of the word containing in the needle sentence
$regex='#'.implode('|',preg_split('#\s#',$search)).'#';
$array_key = array_keys(preg_grep($regex,array_column($list, 'description')));
print_r($array_key);

//second type of search : all of the words containing in the needle sentence
$array_key=[];
$needles=preg_split('#\s#',$search);
$count_needles=count($needles);
$regex='#'.implode('|',$needles).'#';
foreach(array_column($list,'description') as $k=>$v){
    if(preg_replace($regex,'###',$v,-1,$count)){
        if($count===$count_needles) $array_key[]=$k;
    }
}

print_r($array_key);

//third type of search : based on similarity percentage 

$thereshold=50.0;
$array_key=[];
$needles=preg_split('#\s#',$search);
$count_needles=count($needles);
$regex='#'.implode('|',$needles).'#';
foreach(array_column($list,'description') as $k=>$v){
    if(preg_replace($regex,'###',$v,-1,$count)){
        if(min($count,$count_needles)/max($count,$count_needles)*100>$thereshold) $array_key[]=$k;
    }
}

print_r($array_key);

output:

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
)
Array
(
    [0] => 0
    [1] => 1
)
Array
(
    [0] => 0
    [1] => 1
)

array_search - Manual, array_search — Searches the array for a given value and returns the first Returns the key for needle if it is found in the array, FALSE otherwise. About searcing in multi-dimentional arrays; two notes on "xfoxawy at gmail dot Be careful when search for indexes from array_keys() if you have a mixed associative array it  Indexed arrays – Array with numeric indexes. Associative arrays – Array with key-value pairs, its similar to Map in java. Multidimensional arrays – An array of arrays. PHP Indexed arrays. There are two ways to create indexed arrays. – first way to use array() function without any index, index are assigned automatically starting from 0.

I'm not really sure what you want, but I guess this might be a good starting point:

<?php

$list = [
    [
        'name' => 'this is items name',
        'number' =>  1,
        'description' => 'this is description',
        'id' => 'just some id'
    ],

     [
         'name' => 'this is items name2',
        'number' =>  1,
        'description' => 'this is description2',
        'id' => 'just some id'
    ],

    'test' => [
         'name' => 
         'this is items name3',
        'number' =>  1,
        'description' => 'do not find this one',
        'id' => 'just some id'
    ],
    'preserve_this_key_please' => [
         'name' => 
         'this is items name4',
        'number' =>  1,
        'description' => 'this is something, key preserved',
        'id' => 'just some id'
    ],    
];
function getKeysBy($array, $key, $value){
    return array_keys(array_filter($array,function($val) use ($key,$value) {
        //return $val[$key] === $value;//exact match
        return strpos($val[$key], $value) === 0;
    } ));
}
var_dump(getKeysBy($list, 'description', 'this is'));

Output:

array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  string(24) "preserve_this_key_please"
}

Working code:

https://3v4l.org/Gs3He

Note: in this example the keys are preserved, i.e. if a key is a string like in the last item. If you don't need it, then the array_column + friends is enough.

Web Database Applications with PHP and MySQL, If an array of integers is examined , the returned result is an integer , if an array of floats is Finding values in arrays with in _ array ( ) and array _ search ( ) The in _ array contains a specific value needle : boolean in _ array ( mixed needle , array associative and indexed arrays : $ measure = array ( " inch " = > 1 , " foot​  Table 1. Comparison of arrays and associative arrays; Arrays Associative arrays; The maximum cardinality of a simple array is defined when the simple array is defined. When a value is assigned to index N, the elements with indices between the current cardinality of the array and N are implicitly initialized to NULL.

You might use a foreach and preg_match with a regex to match from this until the first occurence of description by matching any character one or more times non greedy .*?:

\bthis.*?description

$result = [];
foreach ($list as $key => $value) {
    if (preg_match('/\bthis.+?description/', $value["description"])) {
        $result[$key] = $key;
    }
}

print_r($result);

Demo

Arrays (Web Database Applications with PHP & MySQL), Arrays in PHP are sophisticated and more flexible than in many other An associative array uses string indexes—or keys—to access values stored in The in_array( ) function returns true if an array haystack contains a specific value needle: type conversion converts the result to false when a Boolean value is required. The array_search () function search an array for a value and returns the key. array_search ( value, array, strict ) Parameter Values. Required. Specifies the value to search for. Required. Specifies the array to search in. Optional. If this parameter is set to TRUE, then this function will search for identical elements in the array. Possible

I'm interpretting your question as: How to search a multidimensional array by searching for multiple needle strings -- all of which are required -- among all of the values in a given subarray and return the index of each qualifying subarray.

My solution seeks direct results by condensing the subarray data into a single string to be checked in an iterative fashion. As soon as a subarray is deemed "disqualified", the loop is directed to process the next subarray for highest efficiency.

*note, if you specifically need to make "whole word" matching then regex with word boundaries will be necessary.

If you are not familiar with what continue does, here is a link to the manual.

Code: (Demo)

$qualifiers = [];
$needles = explode(" ", "this description");

foreach ($list as $index => $set) {
    $smashed = implode($set);
    foreach ($needles as $needle) {
        // echo "\n$smashed";
        if (strpos($smashed, $needle) === false) {
            continue 2;
        }
    }
    $qualifiers[] = $index;
}
var_export($qualifiers);

Output:

array (
  0 => 0,
  1 => 1,
)

p.s. if you are processing a resultset from a database query, it would be better / more direct to perform your filtering task within the query because then you would avoid generating a resultset which is bloated with data that you don't want.

Arr - Classes, The flatten_assoc method flattens a multi-dimensional associative array down into a 1 dimensional It returns an array that contains only the items whose keys are in the $keys array. $key, required, The key to pluck from the arrays. $index, null, Optional return array index. $needle, required, The value to search for. A multimap generalizes an associative array by allowing multiple values to be associated with a single key. A bidirectional map is a related abstract data type in which the mappings operate in both directions: each value must be associated with a unique key, and a second lookup operation takes a value as an argument and looks up the key

3.1 Arrays :: Chapter 3. Arrays, Strings, and Advanced Data , In PHP, as with many programming languages, you can handle these results By creating arrays this way, PHP assigns integer keys, or indexes to each All arrays in PHP are associative with elements accessed either by a string The in_array( ) function returns true if an array haystack contains a specific value needle:. Associative arrays, also called maps or dictionaries, are an abstract data type that can hold data in (key, value) pairs. You can think of associative arrays like a list of phone numbers. In this list, you can look up a person&#39;s name by finding their phone number. The name is the value and the number is the key. This list would look like the following table: Phone Number

Single, Multi-dimensional, Associative and Object Arrays in PHP 7 , □Chapter 7: PHP Functions—Searching, Traversing, and Displaying Arrays 123 PHP 7 and earlier versions of PHP require the Microsoft Visual Studio C# library. the same syntax to declare an associate array we must specify the index (alphabetic “Returns TRUE if needle is found in the array, FALSE otherwise.”. PHP array_multisort is an inbuilt sort Function in PHP. It sorts multiple arrays at once or multi-dimensional arrays.Although it maintains string keys of an Associative Array, it re-indexes all the numerical keys.

How to check an array is associative or sequential in PHP , How to take user input for two dimensional (2D) array in PHP ? PHP Interview Sequential (Indexed) arrays; Associative arrays; Multidimensional arrays. (T/F)In the array_key_exists() function, you pass two arguments: the first represents the key to search for, and the second represents the name of the array in which to search. True (T/F)Use the array_keys() function to return an indexed array containing all the keys in an associative array.

Comments
  • Thinking that array_filter with custom search function can help you to solve the problem
  • what kind of search are you trying to achieve? some kind of similarity percentage?
  • i think you can loop through array and search using strpos function. Or you can use array_search to search but it will search in all values not only description.