【问题标题】:What am I doing wrong with array_walk (and is there a better way)?array_walk 我做错了什么(有没有更好的方法)?
【发布时间】:2015-10-29 07:09:41
【问题描述】:

我有一个名为“方法”的数组,它看起来像这样:

[0] => Array (
    [id] => WWAM
    [title] => WWAM
    [cost] => 4.35
    )
[1] => Array (
    [id] => CNQM
    [title] => CNQM
    [cost] => 5.21
    )
[2] => Array (
    [id] => CNAM
    [title] => CNAM
    [cost] => 6.58
    )

我想要做的是改变每个 [成本] 使得它是 [成本] 减去 (min) [成本]。换句话说,下面的每个将减少 4.35(WWAM 将为零)。可能有更好的方法来解决这个问题,但我想我会尝试 array_walk。但它不适合我。这是我尝试过的:

      $lowestpricedoption = 100000;
      foreach ($methods as $item) {
        if ($item['cost'] < $lowestpricedoption) {
          $lowestpricedoption = $item['cost'];
        }
      }
      array_walk( $methods, 'subtractLowest', $lowestpricedoption );

      function subtractLowest(&$item, $key, $lowestval)
      {
        $item['cost'] -= $lowestval;
      }

我部分想知道为什么这不起作用,但我也希望有一种更优雅的方法。

【问题讨论】:

  • 它有效。重新检查一下。

标签: php arrays array-walk


【解决方案1】:

您可以使用 PHP 的 uasort() 函数,该函数将根据您在 ascending 顺序中的 cost 值对数组进行排序。然后简单地使用 current() 函数和数组解引用,您将获得最低的成本值

uasort($arr, function($a,$b){
    return $a['cost'] - $b['cost'];
});
$min = current($arr)['cost'];
array_walk($arr,function(&$v,$k)use($min){
    $v['cost'] -= $min;
});
print_r($arr);

Demo

【讨论】:

  • 哇!这为我引入了很多新概念。我有一些阅读要做。但有一件事我会在 Google 上玩得很开心......“$result = []”在做什么?
  • 试过了,它确实成功了!我不明白(还),但谢谢!
  • 这里没用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-14
  • 2019-07-21
  • 2014-07-11
  • 2012-12-04
  • 2013-02-23
  • 2022-08-22
  • 1970-01-01
相关资源
最近更新 更多