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

Retrieve key from max value in multidimensional associativ 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 array and Find highest value in multidimensional array.

但结果总是一个空数组。我想 array_keys 当我像我尝试的那样使用关联数组时不起作用。

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

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

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

希望这对您有所帮助,

这个怎么样?

$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

我终于想通了......对于任何可能需要这个的人......

$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。