存储密钥& php

时间:2017-01-04 13:52:53

标签: php arrays

如何在定位到已知密钥后获取数组的键和值?

我的阵列:

[Bolivia] => a
[Brazil] => v
[Belgium] => d
[Cuba] => c
[Croatia] => x
[Finland] => j
[Germany] => m
[India] => n
[Japan] => w

知道密钥: [Croatia]

搜索结果:

[Finland] => j
[Germany] => m
[India] => n
[Japan] => w

2 个答案:

答案 0 :(得分:1)

我会这样解决:

$known_key = 'Croatia';
$input = [....];

$result = [];
$passed = false;
foreach($input as $key => $value){
    if($passed){
        $result[$key] = $value;
    }

    if($key == $known_key){
        $passed = true;
    }
}

答案 1 :(得分:0)

您可以使用array_slice来获取它。

<?php
$array = array(
'Bolivia' => 'a',
'Brazil' => 'v',
'Belgium' => 'd',
'Cuba' => 'c',
'Croatia' => 'x',
'Finland' => 'j',
'Germany' => 'm',
'India' => 'n',
'Japan' => 'w');

$keys = array_keys($array);
$keys_flip = array_flip($keys);
var_dump(array_slice($array, $keys_flip['Croatia'] + 1));

输出:

ei@localhost:~$ php test.php
array(4) {
  ["Finland"]=>
  string(1) "j"
  ["Germany"]=>
  string(1) "m"
  ["India"]=>
  string(1) "n"
  ["Japan"]=>
  string(1) "w"
}