php - 如何按位置获取 PHP 数组中的键?

标签 php arrays array-key

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

  <?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 ...                            
        }
  ?>

感谢您的帮助

最佳答案

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()然后 key() :

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

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

关于php - 如何按位置获取 PHP 数组中的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20320750/

相关文章:

php - 为什么这个简单的 PHP Forloop 不起作用?

arrays - 在 flatMap、flatten 或 map 中哪个先发生?

ios - Cloudkit 返回带有特定字符串的记录

php - 在php中添加一个月

php - 这可以写得更好吗? PHP代码

javascript - 基于 angularjs 中类型列的嵌套列表

php - 如何获取数组中键的位置

php - 从混合数组中删除键并重新索引

php - 查询内容列表的有效方法,每个内容都需要获取标签和类别列表