[英]Return the array position of the containing array
假設我給你以下數組:
$array = array (
array (
'key' => 'value'
),
array (
'key' => 'another value'
),
array (
'key' => 'yet another value'
),
array (
'key' => 'final value'
)
);
我要從此數組中獲得的是具有提供的值的數組的位置。 因此,如果我在$array
搜索"yet another value"
的"yet another value"
則結果應為: 2
因為匹配的數組位於位置2。
我知道要執行以下操作:
foreach ($array as $a) {
foreach ($a as $k => $v) {
if ($v === "yet another value") {
return $array[$a]; // This is what I would do, but I want
// the int position of $a in the $array.
// So: $a == 2, give me 2.
}
}
}
關鍵總是一樣
如果密鑰相同,則只需執行以下操作:
$v = "yet another value";
$a = array_search(array("key"=>$v),$array);
echo $a;//2
http://sandbox.onlinephpfunctions.com/code/1c37819f25369725effa5acef012f9ce323f5425
foreach ($array as $pos => $a) {
foreach ($a as $k => $v) {
if ($v === "yet another value") {
return $pos;
}
}
}
這應該是您想要的。
由於您想要數組的位置,因此請使用count:
var count = 0;
foreach ($array as $a) {
foreach ($a as $k => $v) {
if ($v === "yet another value") {
return count;
}
count++;
}
}
正如您說的那樣,鍵始終是相同的,因此您可以像這樣在循環外聲明一個變量。
$position = 0;
foreach ($array as $a) {
foreach ($a as $k => $v) {
if ($v === "yet another value") {
return $position;
}
}
$position++;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.