note 125022 added to function.array-search
| From: | joe at white-fire dot co dot uk | Date: | Mon, 18 May 2020 09:32:45 +0000 |
| Subject: | note 125022 added to function.array-search | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-214647@lists.php.net to get a copy of this message | ||
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
)
)
----
Server IP: 45.112.84.4
Probable Submitter: 185.85.3.195 (proxied: 80.5.195.101)
----
Manual Page -- http://php.net/manual/en/function.array-search.php
Edit -- https://master.php.net/note/edit/125022
Del: integrated -- https://master.php.net/note/delete/125022/integrated
Del: useless -- https://master.php.net/note/delete/125022/useless
Del: bad code -- https://master.php.net/note/delete/125022/bad+code
Del: spam -- https://master.php.net/note/delete/125022/spam
Del: non-english -- https://master.php.net/note/delete/125022/non-english
Del: in docs -- https://master.php.net/note/delete/125022/in+docs
Del: other reasons-- https://master.php.net/note/delete/125022
Reject -- https://master.php.net/note/reject/125022
Search -- https://master.php.net/manage/user-notes.php