如何按位置获取PHP数组中的键? [英] How to get the keys in a PHP Array by position?
问题描述
我有一个数组,仅当值不为null时才存储键值对.我想知道如何检索数组中的键?
<?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){//遍历数组,并通过一个键获取键...}?>
感谢您的帮助
PHP的foreach循环具有允许您在键/值对上循环的运算符.非常方便:
foreach($ pArray as $ key => $ value){打印$ key}//如果您只想选择第一个键,我将执行以下操作:foreach($ pArray as $ key => $ value){打印$ key;休息;}
此方法的替代方法是调用 reset()
并然后 key()
:
reset($ pArray);$ first_key =键($ pArray);
它与 Thanks for helping PHP's foreach loop has operators that allow you to loop over Key/Value pairs. Very handy: An alternative to this approach is to call It's essentially the same as what is happening in the 这篇关于如何按位置获取PHP数组中的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! 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()
and then key()
:reset($pArray);
$first_key = key($pArray);
foreach()
, but according to this answer there is a little less overhead.