一只名叫tom的猫
正如评论中提到的,array_walk本质上仍然是一个循环,因为它迭代每个元素。我已经记录了每一步的代码,但基本思想是创建一个合并的数组,然后更改重复项的值。有更有效的方法来解决这个问题,但这说明了一种基本方法。我还应该指出,因为这是使用array_walk匿名函数(闭包),我们必须传入它需要的任何变量(... use (...))。如果你使用一个foreach循环(或for),你不会需要做到这一点,你可以访问的$output,$first和$second直接。https://3v4l.org/WD0t4#v7125<?php$first = [ 1 => 4.00, 2 => 3.00, 3 => 8.00, 4 => 4.88, 5 => 7.88, 10 => 17.88];$second = [ 1 => 2.00, 3 => 4.00, 4 => 2.88, 7 => 5.0, 8 => 6.00];// Merge the 2 original arrays and preserve the keys// https://stackoverflow.com/q/17462354/296555// The duplicate items' value will be clobbered at this point but we don't care. We'll set them in the `array_walk` function.$output = $first + $second;// Create an array of the duplicates. We'll use these keys to calculate the difference.$both = array_intersect_key($first, $second);// Foreach element in the duplicates, calculate the difference.// Notice that we're passing in `&$output` by reference so that we are modifying the underlying object and not just a copy of it.array_walk($both, function($value, $key) use (&$output, $first, $second) { $output[$key] = $first[$key] - $second[$key];});// Finally, sort the final array by its keys.ksort($output);var_dump($output);// Output//array (size=8)// 1 => float 2// 2 => float 3// 3 => float 4// 4 => float 2// 5 => float 7.88// 7 => float 5// 8 => float 6// 10 => float 17.88以及使用foreach循环的强制性精简版本。<?php$first = [ 1 => 4.00, 2 => 3.00, 3 => 8.00, 4 => 4.88, 5 => 7.88, 10 => 17.88];$second = [ 1 => 2.00, 3 => 4.00, 4 => 2.88, 7 => 5.0, 8 => 6.00];$output = $first + $second;foreach (array_keys(array_intersect_key($first, $second)) as $key) { $output[$key] = $first[$key] - $second[$key];}ksort($output);var_dump($output);// Output//array (size=8)// 1 => float 2// 2 => float 3// 3 => float 4// 4 => float 2// 5 => float 7.88// 7 => float 5// 8 => float 6// 10 => float 17.88