我試圖在 milti 數組的數組中查找一個值,找到它後,我想返回一個不同的鍵,不知道如何進一步解釋。
我有一個陣列:
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 ))
我正在嘗試透過 [custom_tab_field_id] 來尋找數組,並傳回目前的陣列 [status]。
我創建了一個應該執行此操作的函數,但它總是傳回 0。
功能:
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; }
然後只需透過傳遞值來呼叫該函數
$returnedStatus = searchForStatus($field['custom_tab_field_id'], $tempArr);
P粉4169968282024-04-04 10:24:16
可以使用array-filter
函數來解決。即
$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; }));
它將從與搜尋
id 相符的陣列中傳回整個陣列。
你也可以為此寫一個函數
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
使用 array_column 函數,這可以輕鬆實現已解決並且非常通用。
$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
此解決方案不包含錯誤處理,僅展示原理。 $arrKeyValue 是一個數組,如何:
array ( 17775 => 0, 17776 => 0, 17777 => 2, )