PHP在二维数组中查找数组键

时间:2013-06-28 07:44:23

标签: php search find key multidimensional-array

<?php
$x = array(
       "C_Card_ID" => array(
                              "dbName"=>"CardID",
                              "type"=>"disabled",
                              "key"=>"primary"
                          ),
       "C_Payroll_ID" => array(
                              "dbName"=> "PayrollID",
                              "key"=>"unique"
                          ),
       "C_First_Name" => array("dbName"=>"FirstName")
?>

我希望$x的密钥在其第二个数组中具有"key"索引。简单来说,我需要C_Card_ID和C_Payroll_ID作为数组中的输出,所以稍后我将内爆它们。

Required output Sample : Array("C_Card_ID","C_Payroll_ID")

请不要使用Loop算法。我需要使用一些内置函数。

3 个答案:

答案 0 :(得分:2)

这应该做:

$result = array_keys(array_filter($x, function($arr){
  return array_key_exists('key', $arr);
}));

答案 1 :(得分:2)

尝试使用array_slice()之类的,

<?php
    $x = array(
           "C_Card_ID" => array(
                                  "dbName"=>"CardID",
                                  "type"=>"disabled","key"=>"primary"
                              ),
           "C_Payroll_ID" => array(
                                  "dbName"=> "PayrollID",
                                  "key"=>"unique"
                              ),
           "C_First_Name" => array("dbName"=>"FirstName"));
    print_r(array_slice(array_keys($x),0,2));
    //Outputs
    //Array ( [0] => C_Card_ID [1] => C_Payroll_ID ) 
?>

经过测试 http://writecodeonline.com/php/

答案 2 :(得分:2)

您可以使用array_filter

语法是:

$filtered_array = array_keys(array_filter($x, function($a){ return isset($a['key']); }));