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.
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']
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

