1

如何计算一个包含少量值的字符串的值?

例如,

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

网页显示 2、20 和 50。

我想计算它们并回显到第 72 页。

我试图在网络和该网站上找到解决方案,但我找不到它..

4

2 回答 2

2

似乎是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);
于 2013-02-02T17:13:13.590 回答
1

有几种方法可以处理它,但是对现有代码的简单修改是对您的return值进行修改,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);
于 2013-02-02T17:11:16.587 回答