问题
I have one array and I want to get the positions of one specific value
Example:
$my_array = array(0,2,5,3,7,4,5,2,1,6,9);
My search is Number 5 the positions of Number 5 in array was (2 and 6)
If i call the array_search
function, always returns the first position in array witch is 2.
Is there anyway to get the two ore more positions of specific value?
回答1:
Use array_keys with the optional search parameter, that should return all of the keys.
$matches = array_keys($my_array, 5);
回答2:
Have a look at array_keys second parameter. You can get the keys only matching $search_value
回答3:
Just loop over the array:
/* Searches $haystack for $needle.
Returns an array of keys for $needle if found,
otherwise an empty array */
function array_multi_search($needle, $haystack) {
$result = array();
foreach ($haystack as $key => $value)
if ($value === $needle)
$result[] = $key;
return $result;
}
回答4:
$result = array();
foreach ($array as $key => $value)
{
$result[$value] =implode(',',array_keys($array,$value))
}
echo '<pre>';
print_r($result);
it will give you an array with values as key and their occurrences as values separated by comma
来源:https://stackoverflow.com/questions/12159136/php-array-get-positions-of-the-specific-value