Grab array value if a specific key is there with PHP

后端 未结 3 1995
醉梦人生
醉梦人生 2021-01-27 22:49

I have an array that looks something like this:

Array
(
    [100] => Array
        (
            [room_id] => 100
            [name] => Town Center
             


        
相关标签:
3条回答
  • 2021-01-27 23:08

    Easy use the PHP function array_key_exists

    You may have to go through a foreach loop since you are using a multidimensional array:

    $names = [];
    foreach($array as $e)
    {
      if(array_key_exists('pin_id', $e)) {
            echo "The 'pin_id' element is in the array";
          $names[] = $e['name'];
      }
    }
    

    And now $names include all you names values

    0 讨论(0)
  • 2021-01-27 23:12
    function search_key( $array, $key ) {
        $results = array();
        if ( is_array( $array ) ) {
            if ( isset( $array[$key] ) && $array[$key] == $key )
                $results[] = $array;
            foreach ( $array as $subarray )
                $results = array_merge( $results, tm_search_key_value( $subarray, $key ) );
        }
        return $results;
    }
    

    USAGE:

    search_key( $array, 'pin_id');

    Search specific KEY from Multidimentional, It will return array of that specific key.

    0 讨论(0)
  • 2021-01-27 23:15
    foreach ($your_big_array as $arr) {
        if ($arr['pin_id'] == 'some_value') $i_need_this = $arr['name'];
    }
    
    0 讨论(0)
提交回复
热议问题