如何在 PHP 中没有 foreach 的情况下通过键获取对象项

问题描述 投票:0回答:1

我正在为一些看起来很简单的事情而苦苦挣扎。我有一个包含多个项目的对象,如果没有 foreach,我将无法获得一个项目。

这是我正在谈论的对象:

object(Cake\ORM\ResultSet) id:0 {
'items' => [
(int) 0 => object(App\Model\Entity\Album) id:1 {
'id' => (int) 1
'name' => 'Album 1'
'images' => [ ]
'[new]' => false
'[accessible]' => [ ]
'[dirty]' => [ ]
'[original]' => [ ]
'[virtual]' => [ ]
'[hasErrors]' => false
'[errors]' => [ ]
'[invalid]' => [ ]
'[repository]' => 'Albums'
},
(int) 1 => object(App\Model\Entity\Album) id:5 {
'id' => (int) 3
'name' => 'Album 3'
'images' => [ ]
'[new]' => false
'[accessible]' => [ ]
'[dirty]' => [ ]
'[original]' => [ ]
'[virtual]' => [ ]
'[hasErrors]' => false
'[errors]' => [ ]
'[invalid]' => [ ]
'[repository]' => 'Albums'
},
(int) 2 => object(App\Model\Entity\Album) id:9 {
'id' => (int) 5
'name' => 'Album 5'
'images' => [ ]
'[new]' => false
'[accessible]' => [ ]
'[dirty]' => [ ]
'[original]' => [ ]
'[virtual]' => [ ]
'[hasErrors]' => false
'[errors]' => [ ]
'[invalid]' => [ ]
'[repository]' => 'Albums'
},
]
}

这是我最初认为可行的方法:

$albums['0']

但是它返回这个错误:

Cannot use object of type Cake\ORM\ResultSet as array

搜索后(搜索字符串'php object get first item without foreach',我尝试了一些其他的东西,但没有成功:

$albums->{'1'}
key($albums)

有人可以告诉我这里的灯吗? :)

谢谢!

山姆

php object
1个回答
0
投票

要访问第一个项目,您可以使用

first()

$firstAlbum = $albums->first();

// access the properties
$firstAlbumId = $firstAlbum->id;
$firstAlbumName = $firstAlbum->name;

$albums
Cake\ORM\ResultSet
的一个对象,不能当做数组。要将
ResultSet
对象转换为数组,您可以使用
toArray()
:

$albumsArray = $albums->toArray();
$firstAlbum = $albumsArray[0];
© www.soinside.com 2019 - 2024. All rights reserved.