簡體   English   中英

返回包含數組的數組位置

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM