我想在数组中找到第一个出现的几个值。
$sentence = array(I, want, to, go, to, the, market);
if(in_array(array('swim','fly','go'), $sentence)) {
// Should return KEY = 3 as 'go' was found in the third key of the array
}
我确定这必须相当普遍,怎么办呢?
答案 0 :(得分:1)
http://tr.php.net/manual/en/function.array-keys.php
我想更具体地说你正在寻找这种类型的功能吗?
<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));
$array = array("blue", "red", "green", "blue", "blue");
print_r(array_keys($array, "blue"));
$array = array("color" => array("blue", "red", "green"),
"size" => array("small", "medium", "large"));
print_r(array_keys($array));
?>
以上示例将输出:
Array
(
[0] => 0
[1] => color
)
Array
(
[0] => 0
[1] => 3
[2] => 4
)
Array
(
[0] => color
[1] => size
)
答案 1 :(得分:0)
请使用此函数 array_search 如果在数组中找到元素,它将返回元素的键
实施例
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
答案 2 :(得分:0)
首先你应该正确阅读in_array函数的手册,你是以错误的顺序传递参数
$sentence = array(I, want, to, go, to, the, market);
$found_key = array();
foreach($sentence as $key => $word)
{
if(in_array($word,array('swim','fly','go')))
{ $found_keys[] = $key;}
}
print_r($found_keys);
我希望这就是你需要的东西
答案 3 :(得分:0)
array_keys会起作用。
$keys = array_keys($sentence,array('swim','fly','go');
然后$ keys将是一个键列表,其中游泳,飞行和去出现在$句子
正如以下代码将返回具有空值的键列表
$array = array('one','','three');
$keys = array_keys($array,"");
答案 4 :(得分:0)
function find_in_array($needles,$array) {
$pos = false;
foreach ($needles as $key => $value) {
if (in_array($value, $array)) {
if(!$pos || array_search($value, $array) < $pos) {
$pos = array_search($value, $array);
}
}
}
return $pos;
}
echo find_in_array($values,$sentence);
这就是我现在正在使用的,我正在按照Darian Brown的建议测试array_keys