PHP用foreach來表達array_walk/array_filter/array_map/array_reduce

PHP裝逼玩函數式(回調匿名函數):
array_walk/array_filter/array_map/array_reduce:
遍歷數組,回調函數.遍歷一次,回調一次.
這些邏輯其實均可以用foreach來表達,並且更容易理解.php

array_walk至關於foreach:數組

$arr = ['Client'=>'jQuery','Server'=>'PHP'];
array_walk($arr, function($v, $k) {
    echo "鍵:$k 值:$v\n";
});


好比去除數組$arr元素的先後空白:函數

array_walk($arr, function(&$v) { $v = trim($v); });
foreach($arr as &$v) { $v = trim($v); }

array_filter: 用回調函數過濾數組中的單元,返回過濾後的數組
 code

var_export(
    array_filter([1, 2, 3], function($v) {
        return $v > 1;
    })
);
和
foreach([1, 2, 3] as $k => $v) {
    if($v > 1) {
        $tmp[$k] = $v;
    }
}
var_export($tmp);
都輸出:
array (
  1 => 2,
  2 => 3,
)

PHP數組映射化簡(MapReduce):
array_map/array_reduce回調函數

array_map: 將回調函數做用到給定數組的單元上it

var_export(
    array_map(function ($v) {
        return $v * $v;
    }, [1, 2, 3])
);
和
foreach([1, 2, 3] as $v) {
    $tmp[] = $v * $v;
}
var_export($tmp);
都輸出:
array (
  0 => 1,
  1 => 4,
  2 => 9,
)

array_reduce: 用回調函數迭代地將數組簡化(reduce)爲單一的值io

//輸出16,即10+1+2+3,其中10做爲初始值.
echo array_reduce([1, 2, 3], function($result, $item) {
    $result = $result + $item;
    return $result;
}, 10);
用foreach表達:
$result = 10;
foreach([1, 2, 3] as $v) {
    $result = $result + $v;
}
echo $result;
相關文章
相關標籤/搜索