PHP:使用GET参数过滤数组

时间:2015-06-16 12:51:44

标签: php arrays array-filter

卡住:给出一个像:

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

并给出一个类似?customerID=C01945$_GET['customerID'] = 'C01945')的查询字符串,如何过滤数组以便返回:

$customers = array(
    'C01945' => 'Another one'
)

4 个答案:

答案 0 :(得分:1)

尝试使用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;}});

答案 1 :(得分:1)

简单地做 -

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

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

答案 2 :(得分:1)

您可以使用array_instersect_key

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

答案 3 :(得分:0)

对于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'];}));