在php中處理二維數組時,經常需要根據特定條件提取數據。例如,你可能需要從包含多個項目信息的二維數組中,根據項目的ID提取對應的標題或其他字段的值。
假設你有一個包含項目信息的二維數組:
$items = [ [ "id" => 1, "view" => 2, 'category_id' => 2, 'title' => "項目一", "model" => 12, 'desc' => "項目一描述", ], [ "id" => 123, "view" => 2, 'category_id' => 1, 'title' => "項目二", "model" => 101, 'desc' => "項目二描述", ] ];
你需要根據ID提取特定項目的信息。可以使用以下函數實現:
function getItemValue(array $items, int $itemId, string $key): mixed { foreach ($items as $item) { if ($item['id'] === $itemId) { return $item[$key] ?? NULL; // 使用空值合并運算符處理不存在的鍵 } } return null; // 如果未找到匹配的ID,則返回null } // 獲取ID為123的項目的標題 $title = getItemValue($items, 123, 'title'); echo $title; // 輸出:項目二 // 獲取ID為1的項目的描述 $description = getItemValue($items, 1, 'desc'); echo $description; // 輸出:項目一描述 // 獲取不存在的鍵值,返回null $model = getItemValue($items, 123, 'nonexistent_key'); var_dump($model); // 輸出:NULL
這個函數 getItemValue 接受數組 $items、目標ID $itemId 和目標鍵 $key 作為參數,并返回對應的值。它使用了空值合并運算符 ?? 來處理可能不存在的鍵,并返回 null 如果未找到匹配的ID。 這種方法清晰簡潔,易于理解和維護。
立即學習“PHP免費學習筆記(深入)”;
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END