如何获得对象(stdClass)从数组没有关键


How to get object(stdClass) from array without the key?

我看了看如何从数组中获取对象(stdClass),但答案并没有帮助我。

下面是一个小例子:

Array
(
    [25] => stdClass Object
        (
            [id] => 25
            [name] => FOO
        )
    [27] => stdClass Object
        (
            [id] => 27
            [name] => BAR
        )
)

请注意,位置与ID相同,所以我无法知道确切的位置是什么,所以我不能调用

// since idk how many
$items = array_shift(array_values($array));
$items->name;

// since idk the position
$items = array_shift(array_values($array[0]));
$items->name;

我能找到的唯一解决方案是使用foreach

foreach($array as $item){
    echo '<pre>';
    print_r($item->name);
    echo '</pre>';
}

但这是我最后的资源,因为我有3个子数组,不仅是$array,还有$array['foo'] &&$array['bar'],,$array['foobar']和里面是上面的结构。除此之外,我需要测试内容是否存在,使用if(count($array['foo']) > 0 .

不确定,但我猜你想知道数组的键(位置)是什么。使用array_keys:

$keys = array_keys($array);
// $keys is now array(25, 27)