如何在 PHP 中构建对象数组而不指定索引号?
这是一个奇怪的问题。我正在手动构建一个对象数组,如下所示:
$pages_array[0]->slug = "index";
$pages_array[0]->title = "Site Index";
$pages_array[0]->template = "interior";
$pages_array[1]->slug = "a";
$pages_array[1]->title = "100% Wide (Layout A)";
$pages_array[1]->template = "interior";
$pages_array[2]->slug = "homepage";
$pages_array[2]->title = "Homepage";
$pages_array[2]->template = "homepage";
我喜欢它的清晰性,但因为我必须指定索引号,所以我无法轻松地重新排列它们。如果没有索引号,我该如何做到这一点?相关,有什么更好的方法来做到这一点?
我还尝试通过创建一个类来编写此代码,并使数组上的每个点都是该类的实例。但由于这是一个配置文件,因此很难阅读并知道哪个参数与哪个参数对应。这就是为什么我选择上面这种老式方法的原因。
任何想法都非常感激!
Here is a weird question. I am building an array of objects manually, like this:
$pages_array[0]->slug = "index";
$pages_array[0]->title = "Site Index";
$pages_array[0]->template = "interior";
$pages_array[1]->slug = "a";
$pages_array[1]->title = "100% Wide (Layout A)";
$pages_array[1]->template = "interior";
$pages_array[2]->slug = "homepage";
$pages_array[2]->title = "Homepage";
$pages_array[2]->template = "homepage";
I like how clearcut this is, but because I have to specify the index number, I can't rearrange them easily. How can I do this without the index number? Related, what is a better way to do this?
I also tried writing this by making a class, and having each spot on the array be instances of that class. But since this is a configuration file, it was hard to read and know what argument went with what parameter. That's why I chose this old-school method above.
Any thoughts are much appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
无论如何,此代码
都是无效的 - 如果您没有正确初始化对象,您将收到“严格”警告。所以你必须以某种方式构造一个对象 - 要么使用构造函数:
要么使用 stdclass 强制转换
This code
is invalid anyways - you'll get a "strict" warning if you don't initialize the object properly. So you have to construct an object somehow - either with a constructor:
or using a stdclass cast
如果您使用命名键而不是对象将它们设为数组,则可以这样做:
您可以将其与 Fanis 的解决方案结合起来,如果您愿意,可以使用 slugs 作为键。
If you make them arrays with named keys rather than objects, you can do it like this:
You can combine this with Fanis' solution and use the slugs as the keys if you like.
共有三种方式:
方式一:
方式二:
方式三:
There are three ways:
Way 1 :
Way 2 :
Way 3 :
假设您没有在其他地方设置任何
$pages_array
元素,则可以设置一个简单的变量。您只需记住每次都增加
$i
,这样就不会覆盖元素。Assuming you're not setting any
$pages_array
elements elsewhere, you can set a simple variable.You just have to remember to increment
$i
every time so you don't overwrite an element.假设 slug 是唯一的,也许可以用它来标识您的页面数组:
等
您只需要使用数组键来获取 slug 值。
Assuming the slug will be unique, perhaps use it to identify your page arrays:
etc
You'll just need to use the array key to get your slug value.
如果你想维护序列索引。也许这会有所帮助。
检查
If you want to maintain sequence indexes. May be this will help.
Check