首頁  >  文章  >  後端開發  >  如何在陣列和 lamda 函數上新增函數和篩選器。

如何在陣列和 lamda 函數上新增函數和篩選器。

PHPz
PHPz原創
2024-07-19 14:44:37764瀏覽

How to add function and filter on an array and lamda function.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            display: grid;
            place-items: center;
            font-family: sans-serif;
            height: 100px; 
            margin: 20px; 
        }
    </style>
</head>
<body>
    <h1>You have read in dark mode </h1>

    <?php
    
    function filterBooksByAuthor($books, $author) {
        $filteredBooks = array_filter($books, function($book) use ($author) {
            return $book['author'] == $author;
        });
        return $filteredBooks;
    }

    $books = [
        ['name' => 'Web', 'author' => 'Philip K. Dick', 'purchaseUrl' => 'http://example.com'],
        ['name' => 'OOP', 'author' => 'Andy Weir', 'purchaseUrl' => 'http://example.com'],
        ['name' => 'Database', 'author' => 'Jeffery', 'purchaseUrl' => 'http://example.com']
    ];

    $filteredBooks = filterBooksByAuthor($books, 'Andy Weir');
    ?>

    <!-- Display filtered books -->
    <ul>
        <?php foreach ($filteredBooks as $book) : ?>
            <li><?= $book['name']; ?> - by <?= $book['author'] ?></li>
        <?php endforeach; ?>
    </ul>
    <?php
    $sum = function($a, $b) {
        return $a + $b;
    };

   
    echo "Result of lambda function: " . $sum(3, 4);
    ?>
</body>
</html>

以上是如何在陣列和 lamda 函數上新增函數和篩選器。的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn