PHP在现有对象数组中推入新的键和值

时间:2022-09-25 09:10:34

In my study how objects and arrays work with PHP I have a new problem. Searching in existing questions didn't give myself the right "push".

在我研究对象和数组如何与PHP一起工作时,我遇到了一个新问题。在现有的问题中搜索并没有给自己正确的“推动”。

I have this for example:

我举个例子:

$html_doc = (object) array
    (
    "css"   => array(),
    "js"    => array()
    );
array_push($html_doc , "title" => "testtitle");

Why is this not working? Do i need to specify first the key title? Or is there another "1 line" solution?

为什么它不能工作?我需要先指定键名吗?或者还有其他“一行”解决方案吗?

2 个解决方案

#1


23  

array_push() doesn't allow you to specify keys, only values: use

array_push()不允许指定键,只允许值:use

$html_doc["title"] = "testtitle";

.... except you're not working with an array anyway, because you're casting that array to an object, so use

....除非你不使用数组,因为你把数组转换成对象,所以使用

$html_doc->title = "testtitle";

#2


1  

You can simply use $html_doc["title"] = "testtitle";

只需使用$html_doc["title"] = "testtitle";

Check this comment on the array_push manual page.

检查array_push手册页上的注释。

#1


23  

array_push() doesn't allow you to specify keys, only values: use

array_push()不允许指定键,只允许值:use

$html_doc["title"] = "testtitle";

.... except you're not working with an array anyway, because you're casting that array to an object, so use

....除非你不使用数组,因为你把数组转换成对象,所以使用

$html_doc->title = "testtitle";

#2


1  

You can simply use $html_doc["title"] = "testtitle";

只需使用$html_doc["title"] = "testtitle";

Check this comment on the array_push manual page.

检查array_push手册页上的注释。