我有一个数组,仅当值不为空时才存储键值对。我想知道如何检索数组中的键?
<?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($pArray);
$first_key = key($pArray);
这与 foreach()
中发生的情况基本相同,但根据 this answer开销会少一些。
关于php - 如何按位置获取 PHP 数组中的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20320750/