dongtan4046
2015-03-26 20:26
浏览 18
已采纳

带有一个元素但索引未知的PHP数组。 如何获得?

A function is returning arrays which look like

( [4] => SomeObject )

or

( [2] => SomeObject )

If I know the array will always have only one child how can I access it without knowing the index?

I'm sure PHP has an equivalent to Javascript's getOwnPropertynames, but I would think there must be a more direct way.

Thanks!

图片转代码服务由CSDN问答提供 功能建议

函数返回的数组看起来像

 ([  4] => SomeObject)
   
 
 

 ([2] => SomeObject)
    
 
 

如果我知道数组将始终只有一个子节点,我怎么能在不知道索引的情况下访问它?

我是 确保PHP具有与Javascript的 getOwnPropertynames 相同的功能,但我认为必须有更直接的方式。

谢谢!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dpbf62565 2015-03-26 20:28
    已采纳

    You can use current:

    $value = current($arr);
    

    current returns the value of the element currently pointed to by the array's internal pointer. In this case, that will be the first (and only) element of the array.

    Testing it out:

    function f() {
        return array(4 => 'foo');
    }
    
    $arr = f();
    echo current($arr);
    

    Output:

    foo
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题