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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23916521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:02:17  来源:igfitidea点击:

PHP push new key and value in existing object array

phparraysobjectpush

提问by Dinizworld

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?

为什么这不起作用?我需要先指定密钥标题吗?还是有另一种“1 行”解决方案?

回答by Mark Baker

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

array_push() 不允许您指定键,只能指定值:使用

$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";

回答by Jaaz Cole

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

你可以简单地使用 $html_doc["title"] = "testtitle";

Check this commenton the array_push manual page.

在 array_push 手册页上查看此注释