2

我有一个数组,仅当值不为空时才在其中存储键值对。我想知道如何检索数组中的键?

  <?php
        $pArray = Array();

        if(!is_null($params['Name']))
            $pArray["Name"] = $params['Name'];

        if(!is_null($params['Age']))
            $pArray["Age"] = $params['Age'];

        if(!is_null($params['Salary']))
            $pArray["Salary"] = $params['Salary'];

        if(count($pArray) > 0)
        {
          //Loop through the array and get the key on by one ...                            
        }
  ?>

感谢您的帮助

4

4 回答 4

3

PHP 的 foreach 循环具有允许您遍历键/值对的运算符。非常便利:

foreach ($pArray as $key => $value)
{
    print $key
}

//if you wanted to just pick the first key i would do this: 

    foreach ($pArray as $key => $value)
{
    print $key;
    break;
}

这种方法的另一种方法是调用reset()then key()

reset($pArray);
$first_key = key($pArray);

它与 中发生的情况基本相同foreach(),但根据这个答案,开销会少一些。

于 2013-12-02T04:21:37.230 回答
2

array_keys function will return all the keys of an array.

于 2013-12-02T04:27:38.523 回答
2

为什么不这样做:

foreach($pArray as $k=>$v){
   echo $k . ' - ' . $v . '<br>';
}

那时您将能够看到键及其值

于 2013-12-02T04:22:42.053 回答
2

获取数组键:

$keys = array_keys($pArray);

获取第一把钥匙:

$key = $keys[0];

参考:array_keys()

于 2013-12-02T04:38:03.430 回答