Check if associative array contains value, and retrieve key / position in array

霸气de小男生 提交于 2019-12-18 16:52:21

问题


I'm struggling to explain what I want to do here so apologies if I confuse you.. I'm just as confused myself

I have an array like so:

$foo = array(
    array('value' => 5680, 'text' => 'Red'), 
    array('value' => 7899, 'text' => 'Green'), 
    array('value' => 9968, 'text' => 'Blue'), 
    array('value' => 4038, 'text' => 'Yellow'),
)

I want to check if the array contains the value e.g. 7899 and also get the text linked to that value "Green" in the example above.


回答1:


Try something like this

$foo = array(
    array('value' => 5680, 'text' => 'Red'), 
    array('value' => 7899, 'text' => 'Green'), 
    array('value' => 9968, 'text' => 'Blue'), 
    array('value' => 4038, 'text' => 'Yellow'),
);

$found = current(array_filter($foo, function($item) {
    return isset($item['value']) && 7899 == $item['value'];
}));

print_r($found);

Which outputs

Array
(
    [value] => 7899
    [text] => Green
)

The key here is array_filter. If the search value 7899 is not static then you could bring it in to the closure with something like function($item) use($searchValue). Note that array_filter is returning an array of elements which is why I pass it through current




回答2:


For PHP >= 5.5.0 it is easier with array_column:

echo array_column($foo, 'text', 'value')[7899];

Or to be repeatable without using array_column each time:

$bar = array_column($foo, 'text', 'value');
echo isset($bar[7899]) ? $bar[7899] : 'NOT FOUND!';



回答3:


Taking a guess at what you would like here:

function findTextByValueInArray($fooArray, $searchValue){
    foreach ($fooArray as $bar )
    {
        if ($bar['value'] == $searchValue) {
            return $bar['text'];
        }
    }
}


来源:https://stackoverflow.com/questions/24760004/check-if-associative-array-contains-value-and-retrieve-key-position-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!