如何在PHP中获取数组的直接下一个元素

时间:2014-02-26 10:27:09

标签: php

我有以下形式的数组

$a = array(
      [0] => 
      [address_country] => 
      [1] => 2011-11-29 14:49:10
      [createdtime] => 2011-11-29 14:49:10
    )

我使用for循环

解析此数组
for($i = 0; $i < count($a); $i++){

}

现在我想要解析第二个元素的检索键

For if i = 0,然后我需要某种方式知道它的相应列名是address_country

有什么办法吗?

请注意我必须坚持使用for循环

2 个答案:

答案 0 :(得分:1)

例如,使用array_keys()

$a = array(
      0 => '',
      'address_country' => '',
      '1' => '2011-11-29 14:49:10',
      'createdtime' => '2011-11-29 14:49:10'
    );

$keys = array_keys($a);
$i    = 1;
$m    = count($keys);

foreach($a as $key=>$value)
{
   echo(sprintf('My key is [%s] and my next neighbor key is [%s]'.PHP_EOL, $key, $i<$m?$keys[$i++]:null));
}

这将导致

My key is [0] and my next neighbor key is [address_country]
My key is [address_country] and my next neighbor key is [1]
My key is [1] and my next neighbor key is [createdtime]
My key is [createdtime] and my next neighbor key is []

请注意,对于最后一个元素,下一个键将被视为null

答案 1 :(得分:0)

试试这个。我想这就是你想要的

$c = array_values($a);
for($i = 0; $i < count($c); $i++){
    if(count($c)-1 > ($i)) {
   if(array_search($c[$i+1],$a) == "address_country")
   echo "found";
    }
}