抓住阵列值,如果一个特定的关键是有使用PHP [英] Grab array value if a specific key is there with PHP
本文介绍了抓住阵列值,如果一个特定的关键是有使用PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组,看起来是这样的:
阵列
(
[100] =>排列
(
[ROOM_ID] => 100
[名] =>市中心
) [110] =>排列
(
[ROOM_ID] => 110
[名] =>咖啡店
[pin_id] => 7146
[pin_x] => 570
[pin_y] => 150
)
)
我在想,如果有,我可以得到一个特定的值,如果在pin_id关键是有没有办法。因此,例如:
阵列
(
[100] =>排列
(
[ROOM_ID] => 100
[名] =>镇中心< - 无pin_id,所以我不需要这个值
) [110] =>排列
(
[ROOM_ID] => 110
[名] =>咖啡厅< - 我要获得此值
[pin_id] => 7146< - 既然pin_id关键就在这里
[pin_x] => 570
[pin_y] => 150
)
)
我一直使用的foreach试过,但它得到复杂的我。我还是很新的使用数组,并没有那么熟悉的术语/功能。
解决方案
函数SEARCH_KEY($数组$键){
$结果=阵列();
如果(is_array($阵列)){
如果(使用isset($数组[$关键])及和放大器; $阵列[$关键] == $键)
$结果[] = $阵列;
的foreach($数组作为子阵$)
$结果= array_merge($结果,tm_search_key_value($子数组,$键));
}
返回$结果;
}
用法:
SEARCH_KEY($数组,'pin_id');
搜索从多维特定的键,它会返回一个特定键的数组。
I have an array that looks something like this:
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
)
)
I was wondering if there was a way that I could obtain a specific value, if the "pin_id" key was there. So for example:
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
)
)
I've tried using foreach, but it gets to complicated for me. I'm still very new with arrays, and not so familiar with the terminology/functions.
解决方案
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.
这篇关于抓住阵列值,如果一个特定的关键是有使用PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文