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

问题描述 投票:0回答:3

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

这是我的示例数组

$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不起作用。

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

php arrays associative-array
3个回答
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
投票

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

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


0
投票

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

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

希望这会有所帮助,

© www.soinside.com 2019 - 2024. All rights reserved.