平滑数据数组 PHP
我有一个数组:
Array
(
[1] => 25
[2] => 50
[3] => 25
)
我想将其变成:
Array
(
[1] => 50
[2] => 50
)
为此,我将中间值拆分为 1 和 3。这是最简单的示例,其中拆分为 50,50。 我希望能够将 15 个元素的数组减少到 6 个元素。
有任何想法吗?
其他示例 [10, 15, 20, 25] 简化为两个元素:25(10 + 15),45(20 + 25) [10, 10, 10, 10, 11] 简化为两个元素:25(10 + 10 + (10/2)),26((10/2) + 10 + 11)
I have an array:
Array
(
[1] => 25
[2] => 50
[3] => 25
)
I would like to make it into:
Array
(
[1] => 50
[2] => 50
)
To do this I split the middle value between 1 and 3. This is the simplest example, where the split is 50,50. I would like to be able to take a 15 element array down to 6 elements.
Any ideas?
Additional Examples
[10, 15, 20, 25] Reduced to two elements: 25(10 + 15),45(20 + 25)
[10, 10, 10, 10, 11] Reduced to two elements: 25(10 + 10 + (10/2)),26((10/2) + 10 + 11)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在对彼得的解决方案进行了额外的测试之后,我注意到如果缩小到的大小是奇数,它并没有达到我的预期。 这是我想出的功能。 它还会膨胀小于请求大小的数据集。
After doing additional tests on Peter's solution, I noticed it did not get me what I expected if the reduce to size is an odd number. Here is the function I came up with. It also inflates data sets that are smaller then the requested size.
您可以使用 array_sum() 对值求和,然后根据您想要在结果数组中包含的元素数量,除以该总和并用除法结果填充您想要保留的每个元素。
(这里我假设您将使用第二个数组,但如果您喜欢这种方式,则可以取消设置不需要的数组)。
You could sum the values using array_sum() and then, depending on the number of elements you want to have in your resulting array, divide that sum and fill every element you want to keep with the result of your division.
(Here I'm assuming you'll use a second array, but you could unset the unneeded if you prefer it that way).
这是我对你的问题的看法
Here's my stab at your issue