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

PHP中array_filter过滤多维数组及多重复URL参数取值异常问题

Hey there! Let's tackle your two PHP issues one by one — they're both common gotchas, so you're definitely not alone here.

1. Fixing Multiple Same-Key Request Parameters

The reason you only get the last value when passing City=NY&City=SF is that PHP's default behavior for $_GET/$_POST overwrites duplicate parameter keys, keeping only the final one. Here are two ways to fix this:

Option 1: Adjust the Request Parameter Format

If you have control over how the request is sent, modify the parameter to use array syntax. Change your URL to:
City[]=NY&Category=Population&City[]=SF

With this format, $_GET['City'] will automatically be an array containing both NY and SF, so you can loop through it or use it directly in your filtering logic.

Option 2: Manually Parse the Query String (If You Can't Change the Request)

If you can't adjust the request format, you'll need to parse the raw query string yourself to capture all duplicate keys. Here's a simple function to do that:

function getMultiParams() {
    $queryString = $_SERVER['QUERY_STRING'];
    $params = [];
    
    foreach (explode('&', $queryString) as $pair) {
        if (empty($pair)) continue;
        
        list($key, $value) = explode('=', $pair, 2);
        $key = urldecode($key);
        $value = urldecode($value);
        
        if (isset($params[$key])) {
            // Convert existing value to array if it's not already
            if (!is_array($params[$key])) {
                $params[$key] = [$params[$key]];
            }
            $params[$key][] = $value;
        } else {
            $params[$key] = $value;
        }
    }
    return $params;
}

// Usage:
$requestParams = getMultiParams();
// $requestParams['City'] will now be ['NY', 'SF']
2. Filtering Multidimensional Arrays with array_filter

array_filter works great for one-dimensional arrays, but for multidimensional data (like your database results), you need to pass a custom callback function that tells PHP how to evaluate each sub-array.

Let's say your database returns data like this:

$dbResults = [
    ['City' => 'NY', 'Category' => 'Population', 'Value' => 8336817],
    ['City' => 'SF', 'Category' => 'Population', 'Value' => 883305],
    ['City' => 'LA', 'Category' => 'Area', 'Value' => 503]
];

Example 1: Filter by Category

To get only rows where Category is Population:

$filtered = array_filter($dbResults, function($row) {
    return $row['Category'] === 'Population';
});

Example 2: Combine with Multiple City Values

To filter rows that match any of your City parameters and the Population category:

$cities = $requestParams['City']; // From our earlier function
$filtered = array_filter($dbResults, function($row) use ($cities) {
    // Check if the row's City is in our list and Category matches
    return in_array($row['City'], $cities) && $row['Category'] === 'Population';
});

Calculating the Sum

Once you have your filtered rows, you can calculate the total using array_reduce:

$totalPopulation = array_reduce($filtered, function($sum, $row) {
    return $sum + $row['Value'];
}, 0);

echo "Total Population: " . $totalPopulation; // Outputs 9220122

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:37:12