PHP:使用 GET 参数过滤数组


PHP: Filter an array with a GET parameter

get卡住:给定一个数组,如下所示:

$customers = array(
    'C00005' => 'My customer',
    'C02325' => 'Another customer',
    'C01945' => 'Another one',
    'C00586' => 'ACME inc.'
)

并给定一个像 ?customerID=C01945$_GET['customerID'] = 'C01945') 这样的查询字符串,我如何过滤数组以使其返回:

$customers = array(
    'C01945' => 'Another one'
)
你可以

只使用array_instersect_key

$myKey = $_GET['customerID']; // You should validate this string
$result = array_intersect_key($customers, array($mykey => true));
// $result is [$myKey => 'another customer']

尝试使用 foreach

$customers = array(
    'C00005' => 'My customer',
    'C02325' => 'Another customer',
    'C01945' => 'Another one',
    'C00586' => 'ACME inc.'
);
$_GET['customerID'] = 'C01945';
$result = array();
foreach($customers as $key => $value){
    if($_GET['customerID'] == $key){
        $result[$key] = $value;
    }
}
print_r($result);

使用array_walk

$customerID = 'C01945';
$result = array();
array_walk($customers,function($v,$k) use (&$result,$customerID){if($customerID == $k){$result[$k] = $v;}});

只需 -

$res = !empty($customers[$_GET['customerID']]) ? array($_GET['customerID'] => $customers[$_GET['customerID']]) : false;

您可以使用false或类似的东西来标识空值。

对于 PHP>=5.6:

$customers = array_filter($customers,function($k){return $k==$_GET['customerID'];}, ARRAY_FILTER_USE_KEY);

http://sandbox.onlinephpfunctions.com/code/e88bdc46a9cd9749369daef1874b42ad21a958fc

对于早期版本,您可以帮助自己array_flip

$customers = array_flip(array_filter(array_flip($customers),function($v){return $v==$_GET['customerID'];}));