How to Search by Key=≫Value in a Multidimensional Array in PHP

How to search by key=value in a multidimensional array in PHP

Code:

function search($array, $key, $value)
{
$results = array();

if (is_array($array)) {
if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}

foreach ($array as $subarray) {
$results = array_merge($results, search($subarray, $key, $value));
}
}

return $results;
}

$arr = array(0 => array(id=>1,name=>"cat 1"),
1 => array(id=>2,name=>"cat 2"),
2 => array(id=>3,name=>"cat 1"));

print_r(search($arr, 'name', 'cat 1'));

Output:

Array
(
[0] => Array
(
[id] => 1
[name] => cat 1
)

[1] => Array
(
[id] => 3
[name] => cat 1
)

)

If efficiency is important you could write it so all the recursive calls store their results in the same temporary $results array rather than merging arrays together, like so:

function search($array, $key, $value)
{
$results = array();
search_r($array, $key, $value, $results);
return $results;
}

function search_r($array, $key, $value, &$results)
{
if (!is_array($array)) {
return;
}

if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}

foreach ($array as $subarray) {
search_r($subarray, $key, $value, $results);
}
}

The key there is that search_r takes its fourth parameter by reference rather than by value; the ampersand & is crucial.

FYI: If you have an older version of PHP then you have to specify the pass-by-reference part in the call to search_r rather than in its declaration. That is, the last line becomes search_r($subarray, $key, $value, &$results).

PHP multidimensional array search by value

function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['uid'] === $id) {
return $key;
}
}
return null;
}

This will work. You should call it like this:

$id = searchForId('100', $userdb);

It is important to know that if you are using === operator compared types have to be exactly same, in this example you have to search string or just use == instead ===.

Based on angoru answer. In later versions of PHP (>= 5.5.0) you can use one-liner.

$key = array_search('100', array_column($userdb, 'uid'));

Here is documentation: http://php.net/manual/en/function.array-column.php.

PHP Multidimensional Array Searching (Find key by specific value)

Very simple:

function myfunction($products, $field, $value)
{
foreach($products as $key => $product)
{
if ( $product[$field] === $value )
return $key;
}
return false;
}

How to find the value of a multidimensional array by key

You can try this :

function findByKey($findKey, $array, $result = []) {
foreach ($array as $key => $value) {
if ($key === $findKey) {
$result[] = [$key => $value];
}
if (is_array($value)) {
$result = findByKey($findKey, $value, $result);
}
}
return $result;
}

The idea is to use a recursive function :

  1. you loop through your array
  2. for each key => value, you check if the key is what you want : if yes, add it to the result array, else go next
  3. if the value is an other array, you search inside this array if you have the key you want

Now use it :

$array = [
'type' => 'vacancy',
'needs' => ['root' => 'active'],
'market' => 'shopping',
'red' => 'color',
'education' => 'learning',
'fruits' => [
'red' => 'apple',
'cool' => 'cherry'
]
];

With key type :

$result = findByKey('type', $array);

var_dump($result);

Output is :

array(1) {
[0]=>
array(1) {
["type"]=>
string(7) "vacancy"
}
}

With key red :

$result = findByKey('red', $array);

var_dump($result);

Output is :

array(2) {
[0]=>
array(1) {
["red"]=>
string(5) "color"
}
[1]=>
array(1) {
["red"]=>
string(5) "apple"
}
}

Here is a link to test it : link

How to get an array of specific key in multidimensional array without looping

Since PHP 5.5, you can use array_column:

$ids = array_column($users, 'id');

This is the preferred option on any modern project. However, if you must support PHP<5.5, the following alternatives exist:

Since PHP 5.3, you can use array_map with an anonymous function, like this:

$ids = array_map(function ($ar) {return $ar['id'];}, $users);

Before (Technically PHP 4.0.6+), you must create an anonymous function with create_function instead:

$ids = array_map(create_function('$ar', 'return $ar["id"];'), $users);

PHP Multi Dimensional Array Search returning Keys

Yes it is possible. One solution is to:

  • In the base case utilize array_search() to get the key.
  • In the recursive case, when iterating over each element in the haystack (before recursing) use the $key => $value syntax of foreach. Then when the recursive call yields a value, check if the returned value is an array (by using is_array()) - if so, use array_unshift() to push the current key onto the returned array. Otherwise return an array with the key and the returned value.

    function search_array($needle, $haystack) {
    if(in_array($needle, $haystack)) {
    return array_search($needle, $haystack);
    }
    foreach($haystack as $key => $element) {
    if(is_array($element) && search_array($needle, $element)) {
    $searchReturn = search_array($needle, $element);
    if (is_array($searchReturn)) {
    array_unshift($searchReturn, $key);
    return $searchReturn;
    }
    return [$key, $searchReturn];
    }
    }
    return false;
    }

See it demonstrated in this playground example.

Find Key value in nested Multidimensional Array

Here's my approach at writing a function to check the keys of your array using the Recursive Iterator classes...

function isArrayKeyAnywhere( $array, $searchKey )
{
foreach( new RecursiveIteratorIterator( new RecursiveArrayIterator( $array ), RecursiveIteratorIterator::SELF_FIRST ) as $iteratorKey => $iteratorValue )
{
if( $iteratorKey == $searchKey )
{
return true;
}
}
return false;
}

$array = [
'abc'=>[],
'def'=>[],
'hij'=>[
'media'=>[
'video_info'=>[
'video_variants'=>[
[],
[]
]
]
]
]
];

var_dump( isArrayKeyAnywhere( $array, 'video_info' ) ); // true
var_dump( isArrayKeyAnywhere( $array, 'foo_bar' ) ); // false


Related Topics



Leave a reply



Submit