I'm trying to find a value in an array of milti arrays and after finding it I want to return a different key, not sure how to explain further.
I have an array:
tempArray( [0] => Array
(
[id] => 18460
[field_id] => 14
[parent_id] => 165
[custom_tab_field_id] => 17775
[status] => 0
[field_type] => 0
)
[1] => Array
(
[id] => 18461
[field_id] => 2
[parent_id] => 165
[custom_tab_field_id] => 17776
[status] => 0
[field_type] => 2
)
[2] => Array
(
[id] => 18462
[field_id] => 12
[parent_id] => 165
[custom_tab_field_id] => 17777
[status] => 2
[field_type] => 2
))
I'm trying to find an array by [custom_tab_field_id] and return the current array [status].
I created a function that is supposed to do this, but it always returns 0.
Function:
function searchForStatus($id, $array){
$returnedStatus = "0";
foreach ($array as $key => $val){
if ($val['custom_tab_field_id'] == $id){
return $returnedStatus = $array[$key]['status'];
}
}
return $returnedStatus;
}
Then just call the function by passing the value
$returnedStatus = searchForStatus($field['custom_tab_field_id'], $tempArr);
Can be solved using the
array-filterfunction. Right now$a1 = [ ['id' => 1, 'status', 'active'], ['id' => 2, 'status', 'in-active'] ]; $search = 2; print_r(array_filter($a1, function ($object) use ($search) { return $object['id'] == $search; }));It will return the entire array from the array matching the
searchid.You can also write a function for this
function search($data, $searchValue, $searchField, $returnField) { $filter = array_filter($data, function ($object) use ($searchValue, $searchField) { return $object[$searchField] == $searchValue; }); return count($filter) > 0 ? $filter[0][$returnField] : null; }Using the array_column function, this can be easily solved and is very general.
This solution does not include error handling, it only shows the principle. $arrKeyValue is an array, how to:
Try it yourselfhttps://3v4l.org/SnVM4