假設目前有陣列
$fruits = [
['id'=>0,'fruit'=>'apple','sweetness'=>2,'price'=>20],
['id'=>1,'fruit'=>'banana','sweetness'=>4,'price'=>15],
['id'=>2,'fruit'=>'grape','sweetness'=>5,'price'=>80],
['id'=>3,'fruit'=>'orange','sweetness'=>1,'price'=>70],
];
用來更新陣列中的值,產生出新的陣列。
$nfruits = array_map(function($fruit){
$fruit['price'] = $fruit['price'] *2;
return $fruit;
},$fruits);
print_r($nfruits);
就能取得一個price翻倍的新陣列
另外,也能將function函式提到array_map外,也能得到相同的結果
function doublePrice($fruit)
{
$fruit['price'] = $fruit['price'] *2;
return $fruit;
}
$nfruits = array_map("doublePrice",$fruits);
print_r($nfruits);
也能利用array_map做到陣列之間的比較
array_map("function",陣列一,陣列二,...);
function doublePrice($fruit,$a)
{
if($fruit['fruit'] == $a)
return "same";
return "different";
}
$array = array("apple","lemon","pineaple","orange");
$nfruits = array_map("doublePrice",$fruits,$array);
print_r($nfruits);