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);
P粉4169968282024-04-04 10:24:16
Can be solved using the array-filter
function. 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 search
id.
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; }
P粉9211300672024-04-04 09:24:48
Using the array_column function, this can be easily solved and is very general.
$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
This solution does not include error handling, it only shows the principle. $arrKeyValue is an array, how to:
array ( 17775 => 0, 17776 => 0, 17777 => 2, )
Try it yourselfhttps://3v4l.org/SnVM4