Wasim A.
Wasim A.

Reputation: 9890

PHP find array key in two dimension 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")
?>

I want keys of $x which has "key" index in its second array. In simple words, i need C_Card_ID and C_Payroll_ID as an output in array, so later i will implode them.

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

Please don't use Loop algo. I need to use some build-in function.

Upvotes: 1

Views: 142

Answers (3)

user409460
user409460

Reputation:

You can use array_filter:

syntax is:

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

Upvotes: 2

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try to use array_slice() like,

<?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 ) 
?>

Tested on http://writecodeonline.com/php/

Upvotes: 2

elclanrs
elclanrs

Reputation: 94101

This should do:

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

Upvotes: 2

Related Questions