You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP二维数组查找最大值完整键及max函数使用困惑求助

Understanding PHP Multi-Dimensional Arrays & Fixing Your Max Key Issue

Hey there! Let's break down what's going on with your PHP array problems step by step—this is a super common gotcha with how PHP handles multi-dimensional arrays, so you're not alone here.

First: Why max($array) didn't return 7000

The confusion starts with how PHP's max() function works on arrays of arrays. It doesn't recursively scan every single element to find the highest value. Instead, it compares the subarrays themselves using PHP's array comparison rules, which are similar to dictionary sorting:

  • Arrays are compared element by element, starting from the first index.
  • The first subarray with a larger element at the same position is considered "bigger" overall.

Let's look at your second example array:

$array[0] = [5323, 5346, 5424];
$array[1] = [6000, 5412, 5543];
$array[2] = [5651, 7000, 5254];

When max($array) runs:

  1. It compares $array[0] vs $array[1]: the first element of $array[1] is 6000, which is bigger than $array[0]'s 5323. So $array[1] is now the temporary "max".
  2. Next, it compares $array[1] vs $array[2]: the first element of $array[1] is 6000, which is bigger than $array[2]'s 5651. So $array[1] stays the max, even though $array[2] has the 7000 value later on.

That's why var_dump(max($array)) returned the subarray with 6000 instead of 7000—PHP wasn't looking for the highest individual value, it was looking for the "largest" subarray.

Second: Why array_search(max($array), $array) only gives part of the key

When you run max($array) on your first example ([[1,2],[3,4]]), it returns the subarray [3,4] (since it's the "largest" subarray). Then array_search() finds the key of this subarray in the parent array, which is 1. But this only gives you the outer key—you still need to find the inner key of the max value within that subarray.

Your original code only does one level of search, so it can't get the full [1][1] path.

The Solution: A Custom Function to Find the Max Value & Full Key

To get the complete key path (like [1][1] or [2][1]), you need to loop through every element in the multi-dimensional array, track the highest value, and record its outer and inner keys. Here's a simple function for your 2D array case:

function getMaxWithFullKey($twoDArray) {
    $maxValue = null;
    $fullKey = [];

    foreach ($twoDArray as $outerKey => $innerArray) {
        foreach ($innerArray as $innerKey => $currentValue) {
            // Initialize max value on first iteration, or update if current is larger
            if ($maxValue === null || $currentValue > $maxValue) {
                $maxValue = $currentValue;
                $fullKey = [$outerKey, $innerKey];
            }
        }
    }

    return [
        'max_value' => $maxValue,
        'full_key' => $fullKey // Will be like [1,1] or [2,1]
    ];
}

Testing this with your arrays

For your first array:

$array = [[1,2],[3,4]];
$result = getMaxWithFullKey($array);
echo "Max value: " . $result['max_value'] . "\n"; // Outputs 4
echo "Full key: [" . implode('][', $result['full_key']) . "]"; // Outputs [1][1]

For your second array:

$array = [
    [5323, 5346, 5424],
    [6000, 5412, 5543],
    [5651, 7000, 5254]
];
$result = getMaxWithFullKey($array);
echo "Max value: " . $result['max_value'] . "\n"; // Outputs 7000
echo "Full key: [" . implode('][', $result['full_key']) . "]"; // Outputs [2][1]

Bonus: For deeper multi-dimensional arrays

If you ever need to handle 3D or deeper arrays, you can modify the function to be recursive. But for your current 2D use case, the above function works perfectly.

Recap of Key Takeaways

  • max($array) on a 2D array compares subarrays, not individual elements—don't use it to find the highest value across all elements.
  • array_search() only finds the key of the item you're searching for in the immediate array it's given.
  • To get the full key path of the maximum value, loop through every element explicitly and track the keys as you go.

内容的提问来源于stack exchange,提问作者leyanes212

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 10:52:37