从多维关联数组中的最大值中检索键

时间:2019-11-29 14:54:28

标签: php arrays associative-array

我尝试从多维数组中的最大值获取密钥。

这是我的样本数组

$resultCache[129] = [
    'total'                => 1000,
    'free_from'            => "2000",
    'addinupshippingcosts' => "0",
    'articles'             => [
        ['shipping_costs_total' => 25], //<= i want the key of this array entry
        ['shipping_costs_total' => 12],
    ]
];

首先,我认为我可以参加

foreach($resultCache as $s => $r){
    $highest = array_keys(
        $resultCache[$s]['articles'],
        max(array_column($resultCache[$s]['articles'], 'shipping_costs_total'))
    );
}

自从我受到启发

Return index of highest value in an arrayFind highest value in multidimensional array

但是结果总是一个空数组。我猜想当我像尝试使用associativ数组时array_keys不起作用。

还有其他方法可以实现吗?当然不用我自己收集值。

3 个答案:

答案 0 :(得分:2)

怎么样?

$max = array_column($resultCache[129]['articles'], 'shipping_costs_total');
arsort($max);
reset($max);
$first_key = key($max);
echo $first_key;

如果您已(PHP 7> = 7.3.0),则

$max = array_column($resultCache[129]['articles'], 'shipping_costs_total');
arsort($max);
reset($max);
echo array_key_first($max);

工作演示: https://3v4l.org/t472P

答案 1 :(得分:1)

根据您的回答,我建议进行以下小调整:

<?php
$resultCache[129] = [
    'total'                => 1000,
    'free_from'            => "2000",
    'addinupshippingcosts' => "0",
    'articles'             => [
        ['shipping_costs_total' => 11],
        ['shipping_costs_total' => 23],
        ['shipping_costs_total' => 25], //<= i want the key of this array entry
        ['shipping_costs_total' => 12],
    ]
];

foreach($resultCache as $r) {
    $col = array_column($r['articles'], 'shipping_costs_total');
    $highest = array_keys($col, max($col));
    $highest = $highest[0] ?: false;
    echo $highest;
}

希望这会有所帮助,

答案 2 :(得分:1)

我最终想出了...。适合任何可能需要此服务的人...

$resultCache[129] = [
    'total'                => 1000,
    'free_from'            => "2000",
    'addinupshippingcosts' => "0",
    'articles'             => [
        ['shipping_costs_total' => 25], //<= i want the key of this array entry
        ['shipping_costs_total' => 12],
    ]
];

foreach($resultCache as $s => $r){
    $highest = array_keys(
        array_column($r['articles'], 'shipping_costs_total'),
        max(array_column($r['articles'], 'shipping_costs_total'))
    );
    echo $highest[0]
}

显然,传递的数组也需要array_column。