note 125022 deleted from function.array-search by crell
| From: | crell@php.net | Date: | Thu, 31 Mar 2022 20:44:58 +0000 |
| Subject: | note 125022 deleted from function.array-search by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-217960@lists.php.net to get a copy of this message | ||
Note Submitter: joe at white-fire dot co dot uk
----
By extension of
sunelbe at gmail dot com solution to search for a specific array
element with key value in a multidimensional array, this one also returns the parent.
<?php
function array_search_multi(
$array,
$key,
$value,
$parent = false
) {
$results = array();
if (is_array($array)) {
if (isset($array[$key]) && $array[$key] == $value)
$results[] = $array;
foreach ($array as $id => $subarray) {
$found = array_search_multi(
$subarray, $key, $value
);
if(!empty($found)) {
if($parent) {
$results[$id] =
$array[$id];
} else {
$results = $found;
}
}
}
}
return $results;
}
$array = array(
'key1' => array(
'ID' => 1,
'key2' => array(
'ID' => 2,
'key3' => array(
'ID' => 3
)
)
),
'key4' => 4,
'key6' => array(
'ID' => 5,
'key7' => array(
'ID' => 6,
'key8' => array(
'ID' => 7,
'value' => 'test'
)
)
)
);
array_search_multi($array, 'ID', 7, false);
[0] => Array
(
[ID] => 7
[value] => test
)
array_search_multi($array, 'ID', 7, true);
[key6] => Array
(
[ID] => 5
[key7] => Array
(
[ID] => 6
[key8] => Array
(
[ID] => 7
[value] => test
)
)