andil01
andil01

Reputation: 375

php checking if value exist in a 2 level multidimensional array

I have this array:

Array
(
    [01] => Array
        (
            [cat_id] => 15
            [offset] => 4951
        )

    [02] => Array
        (
            [cat_id] => 15
            [offset] => 4251
        )

    [03] => Array
        (
            [cat_id] => 15
            [offset] => 4001
        )

    [04] => Array
        (
            [cat_id] => 15
            [offset] => 4951
        )

    [05] => Array
        (
            [cat_id] => 15
            [offset] => 3301
        )
)

I have the code to get the key on first level using array_key_exists;

if ((array_key_exists("01", $completed_steps))) {
     echo "Found 0!";
}

But I want now to get the cat_id value, how could I do that in a level 2 array?

Upvotes: 2

Views: 1426

Answers (4)

Hari
Hari

Reputation: 1623

use the code below

$final_cat_id_array = array();
$key_to_check = 'cat_id';

$catFunc = function($currentArr) use (&$final_cat_id_array, $key_to_check){
  if(is_array($currentArr) && array_key_exists($key_to_check, $currentArr)){
     $final_cat_id_array[] = $currentArr[$key_to_check];
    }
};

  $arr = array(
     "01" => array("cat_id" => 1, "offset" => true),
     "02" => array("cat_id" => 2, "offset" => false),
     "03" => array("cat_id" => 3, "offset" => true),
  );

 array_walk($arr, $catFunc);

 print_r($final_cat_id_array);

the final $final_cat_id_array will have all the cat_id.

Upvotes: 0

Jigar Shah
Jigar Shah

Reputation: 6223

Use below code, it will find key to n-level depth and search for given key

function multiKeyExists(array $arr, $key) {

    // is in base array?
    if (array_key_exists($key, $arr)) {
        return $arr[$key]['cat_id']; // returned cat_id 
    }

    // check arrays contained in this array
    foreach ($arr as $element) {
        if (is_array($element)) {
            if (multiKeyExists($element, $key)) {
                return $element[$key]['cat_id']; // returned cat_id
            }
        }

    }

    return false;
}

Upvotes: 2

B. Desai
B. Desai

Reputation: 16436

You can get particular key-value from it index. See following example:

$check_key = "01";
if ((array_key_exists($check_key, $completed_steps))) {
     echo "Found 0! value of cat_id  = ".$completed_steps[$check_key]['cat_id'];
} 

Upvotes: 0

Luka Peharda
Luka Peharda

Reputation: 1013

Try like this:

if ((array_key_exists('cat_id', $completed_steps['01'])) {
   echo $completed_steps['01']['cat_id'];
}

Upvotes: 0

Related Questions