【问题标题】:Getting the max, min and avg of an array [duplicate]获取数组的最大值、最小值和平均值
【发布时间】:2021-02-17 12:26:04
【问题描述】:

我有一个看起来像这样的数组

array:3 [
    0 => {
        "id": "1"
        "name": "Product 1"
        "price": "123"
    }
    1 => {
        "id": "2"
        "name": "Product 2"
        "price": "23"
    }
    2 => {
        "id": "3"
        "name": "Product 3"
        "price": "234"
    }
]

我试图找到数组的最大值、最小值和平均值。 我不确定我应该寻找什么或应该如何做这个

【问题讨论】:

  • 我们是否应该假设您的意思是此数组中price 的 Max、Min 和 Avg?
  • 您可能希望以array_column 开头。之后 min 和 max 就变得微不足道了,通过使用同名函数,以及如何计算数组的平均值,你应该可以很容易地自己研究。
  • @RiggsFolly - 抱歉忘了提,但是是的,这是为了价格
  • 类似的Q&A

标签: php


【解决方案1】:

就像在 cmets 中指出的那样,您可以使用 array_column

<?php

$arr = [
    0 => [
        "id"    => "1",
        "name"  => "Product 1",
        "price" => "123",
    ],
    1 => [
        "id"    => "2",
        "name"  => "Product 2",
        "price" => "23",
    ],
    2 => [
        "id"    => "3",
        "name"  => "Product 3",
        "price" => "234",
    ],
];

$prices = array_column($arr, 'price');
echo "minimum: " . min($prices) . "\n";
echo "maximum: " . max($prices) . "\n";
echo "average: " . (array_sum($prices) / count($arr)) . "\n";

【讨论】:

    猜你喜欢
    • 2018-07-01
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 2012-04-13
    • 1970-01-01
    相关资源
    最近更新 更多