简体   繁体   中英

How to check if a value exists in a Multidimensional array

I have an Multidimensional array that takes a similar form to this array bellow.

  $shop = array( array( Title => "rose", Price => 1.25, Number => 15 ), array( Title => "daisy", Price => 0.75, Number => 25, ), array( Title => "orchid", Price => 1.15, Number => 7 ) ); 

I would like to see if a value I'm looking for is in the array, and if so, return the position of the element in the array.

Here's a function off the PHP Manual and in the comment section.. Works like a charm.

<?php
function recursive_array_search($needle,$haystack) {
    foreach($haystack as $key=>$value) {
       $current_key=$key;
       if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
            return $current_key;
        }
    }
    return false;
}

Found this function in the PHP docs: http://www.php.net/array_search

A more naive approach than the one showed by Zander, you can hold a reference to the outer key and inner key in a foreach loop and store them.

$outer = "";
$inner = "";
foreach($shop as $outer_key => $inner_array){
  foreach($inner_array as $inner_key => $value) {
    if($value == "rose") {
      $outer = $outer_key;
      $inner = $inner_key;
      break 2;
    }
  }
}

if(!empty($outer)) echo $shop[$outer][$inner];
else echo "value not found";

You can use array_map with in_array and return the keys you want

$search = 1.25; 

print_r(

array_filter(array_map(function($a){

    if (in_array($search, $a)){
        return $a;
    }

}, $shop))

);

Will print:

Array
(
    [0] => Array
        (
            [Title] => rose
            [Price] => 1.25
            [Number] => 15
        )

)

php >= 5.5

$shop = array( array( 'Title' => "rose", 
                  'Price' => 1.25,
                  'Number' => 15 
                ),
           array( 'Title' => "daisy", 
                  'Price' => 0.75,
                  'Number' => 25,
                ),
           array( 'Title' => "orchid", 
                 'Price' => 1.15,
                  'Number' => 7 
                )
         );

         $titles = array_column($shop,'Title');

        if(!empty($titles['rose']) && $titles['rose'] == 'YOUR_SEARCH_VALUE'){
            //do the stuff
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM