I'm trying to find a value in a milti array's array, and after finding it, I want to return a different key, not sure how to explain it 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 the array by [custom_tab_field_id], and return the current's array [status].
I created a function that should do just that, but it's always returning 0.
The 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;
}
and then simply call for the function by passing values
$returnedStatus = searchForStatus($field['custom_tab_field_id'], $tempArr);
CodePudding user response:
With the array_column function, this can be easily solved and is very universal.
$array = [
['id' => 18460, 'field_id' => 14, 'parent_id' => 165, 'custom_tab_field_id' => 17775, 'status' => 0, 'field_type' => 0],
['id' => 18460, 'field_id' => 2, 'parent_id' => 165, 'custom_tab_field_id' => 17776, 'status' => 0, 'field_type' => 2],
['id' => 18460, 'field_id' => 14, 'parent_id' => 165, 'custom_tab_field_id' => 17777, 'status' => 2, 'field_type' => 2],
];
$findKey = 'custom_tab_field_id';
$getKey = 'status';
$findVal = 17777;
$arrKeyValue = array_column($array,$getKey,$findKey);
$status = $arrKeyValue[$findVal]; //2
The solution contains no error handling and only shows the principle. $arrKeyValue is a array how:
array (
17775 => 0,
17776 => 0,
17777 => 2,
)
try self on https://3v4l.org/SnVM4
CodePudding user response:
you can use array-filter
function to solve it. i.e.
$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 whole array from the array that matches the search
id.
you can also write a function for that
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;
}