如果PHP中存在特定键,则获取数组值

时间:2013-03-10 01:24:32

标签: php arrays

我有一个看起来像这样的数组:

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

    [110] => Array
        (
            [room_id] => 110
            [name] => Coffee Shop
            [pin_id] => 7146
            [pin_x] => 570
            [pin_y] => 150
        )
)

我想知道是否有一种方法可以获得特定值,如果“pin_id”键存在的话。例如:

Array
(
    [100] => Array
        (
            [room_id] => 100
            [name] => Town Center     <-- No "pin_id" so I DON'T need this value
        )

    [110] => Array
        (
            [room_id] => 110
            [name] => Coffee Shop     <-- I want to OBTAIN this value
            [pin_id] => 7146          <-- Since the "pin_id" key is here
            [pin_x] => 570
            [pin_y] => 150
        )
)

我尝试过使用foreach,但它对我来说很复杂。我对数组还很新,对术语/函数不太熟悉。

3 个答案:

答案 0 :(得分:0)

轻松使用PHP函数array_key_exists

<?php
$search_array = array('pin_id' => 1, 'second' => 4);
if (array_key_exists('pin_id', $search_array)) {
    echo "The 'pin_id' element is in the array";
}
?>

* *编辑阅读完你后,你可能需要经历一个foreach循环,因为你使用的是多维数组

foreach($array as $arr)
{
  if(array_key_exists('pin_id', $arr)) {
        echo "The 'pin_id' element is in the array";
  }
}

答案 1 :(得分:0)

foreach ($your_big_array as $arr) {
    if ($arr['pin_id'] == 'some_value') $i_need_this = $arr['name'];
}

答案 2 :(得分:0)

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;
}

用法:

search_key($ array,'pinid');

从多维搜索特定的KEY,它将返回该特定键的数组。