2013-02-02 38 views
1

如何计算一个包含少量值的字符串的值?如何计算array_map函数中的两个值

例如,

$toPluck = 'price'; 
$arr = $gamesWorth; 
$plucked = array_map(function($item) use($toPluck) { 
    echo $item[$toPluck]; 
}, $arr); 

该网页显示2,20,和50

我想计算他们两个,并显示到页面上72

我试图找到一个解决方案在网站上,但我找不到它..

回答

0

有几种方法来处理它,但对现有代码的简单修改将是您的array_map()中的值为,并将结果数组与array_sum()相加。

$toPluck = 'price'; 
$arr = $gamesWorth; 
$plucked = array_map(function($item) use($toPluck) { 
    // Uncomment this if you want to print individual values 
    // Otherwise the array_map() produces no output to the screen 
    // echo $item[$toPluck]; 

    // And return the value you need 
    return $item[$toPluck]; 
}, $arr); 

// $plucked is now an array 
echo array_sum($plucked); 
1

似乎是array_reduce

$toPluck = 'price'; 
$arr = array(
    array('price' => 2), 
    array('price' => 20), 
    array('price' => 50), 
); 

echo array_reduce($arr, function($sum, $item) use($toPluck) { 
    return $sum + $item[$toPluck]; 
}, 0); 
工作