0

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

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,但它对我来说变得很复杂。我对数组还是很陌生,对术语/函数不太熟悉。

4

3 回答 3

1

轻松使用PHP功能array_key_exists

foreach由于您使用的是多维数组,因此您可能必须经历一个循环:

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

现在$names包括所有你的名字值

于 2013-03-10T01:26:29.877 回答
0
foreach ($your_big_array as $arr) {
    if ($arr['pin_id'] == 'some_value') $i_need_this = $arr['name'];
}
于 2013-03-10T02:40:30.753 回答
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, 'pin_id');

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

于 2014-03-28T12:39:45.090 回答