php 使用array_walk生成新的數組

array_walk(array,myfunction,userdata...)

array_walk() 函數對數組中的每一個元素應用回調函數。若是成功則返回 TRUE,不然返回 FALSE。
典型狀況下  myfunction  接受兩個參數。
array  參數的值做爲第一個,鍵名做爲第二個。
若是提供了可選參數  userdata  ,將被做爲第三個參數傳遞給回調函數。
$a = ['a' => 'red', 'b' => 'green', 'c' => 'blue'];
$data = [];

$myfunction = function ($value, $key) use (&$data) {
$data[] = sprintf('"The key %s has the value %s', $key, $value);
};

array_walk($a, $myfunction);
var_dump($data);

執行結果,$data 輸出以下:php

$ php -f depakin.php
array(3) {
  [0]=>
  string(27) "The key a has the value red"
  [1]=>
  string(29) "The key b has the value green"
  [2]=>
  string(28) "The key c has the value blue"
}
相關文章
相關標籤/搜索