I need to filter a multidimensional array by the value of a sub-array which might be on a different position each time.
The following array
array(3) {
[147]=>
array(2) {
[0]=>
int(4)
[1]=>
string(3) "req"
}
[199]=>
array(2) {
[0]=>
int(5)
[1]=>
string(3) "opt"
}
[212]=>
array(3) {
[0]=>
int(2)
[1]=>
int(5)
[2]=>
string(3) "req"
}
needs to be split into these arrays.
Array 1:
array(2) {
[147]=>
array(2) {
[0]=>
int(4)
[1]=>
string(3) "req"
}
[212]=>
array(3) {
[0]=>
int(2)
[1]=>
int(5)
[2]=>
string(3) "req"
}
Array 2:
array(1) {
[199]=>
array(2) {
[0]=>
int(5)
[1]=>
string(3) "opt"
}
I know of array_filter() but can´t figure out the function inside array_filter() that gives me the desired result.
I tried
$req = array_filter($my_array, function ($v, $k) {
return $v == 'req';
}, ARRAY_FILTER_USE_BOTH);
I also tried
function filter_my_array($my_array, $search_term) {
$new_array = array();
foreach ($my_array as $subarray) {
if (in_array($search_term, $subarray)) {
$new_array[] = $subarray;
}
}
return $new_array;
}
$req = filter_my_array($array, 'req');
Both approaches do not work.
You can create two arrays with the help of filtering by necessary values. You can use array_filter function to it, but you should find a necessary value in each element that passed to array_filter function.
For example, finding 'req' value
$req = array_filter($my_array, function ($v) {
return in_array('req', $v);
});
For example, finding 'opt' value
$opt = array_filter($my_array, function ($v) {
return in_array('opt', $v);
});
I used in_array function to finding values because each element is an array that has different quantity of elements
This seems to work for me:
function filter_my_array($my_array, $search_term) {
$required_array = [];
$filtered_array = [];
foreach ($my_array as $key => $subarray) {
$found_flag = false;
foreach ($subarray as $cur_subarray) {
if ($cur_subarray == $search_term) {
$found_flag = true;
break;
}
}
if ($found_flag == true) {
$required_array[$key] = $subarray;
} else {
$filtered_array[$key] = $subarray;
}
}
return [$required_array, $filtered_array];
}
To retrieve the required array and the filtered array, call the function as follows:
list($required_array, $filtered_array) = filter_my_array($my_array, 'req');
where $my_array holds the array in your example.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.