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);
Advertisement
Answer
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