简体   繁体   English

我对array_walk做错了什么(还有更好的方法)吗?

[英]What am I doing wrong with array_walk (and is there a better way)?

I have an array called "methods" and it looks like so: 我有一个名为“方法”的数组,看起来像这样:

[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
    )

What I want to do is alter each [cost] such that it is [cost] minus (min)[cost]. 我想做的是更改每个[成本],使其为[成本]减去(min)[成本]。 In other words, each one below would be reduced by 4.35 (the WWAM one would then be zero). 换句话说,下面的每一位将减少4.35(WWAM则为零)。 There's probably a better way to go about this, but I figured I'd try array_walk. 可能有更好的方法可以解决此问题,但是我想尝试一下array_walk。 It isn't working out for me though. 不过,这对我来说并不奏效。 Here's what I tried: 这是我尝试过的:

      $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;
      }

I partly want to know why that isn't working, but I also would appreciate a more elegant method. 我部分地想知道为什么该方法不起作用,但是我也希望使用一种更优雅的方法。

You can use uasort() function of PHP that'll sort your array as per your cost value within ascending order. 您可以使用PHP的uasort()函数,该函数将根据您的costascending对数组进行排序。 And then simply use the current() function along with the array dereferencing and you'll get the lowest value of 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 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM