PHP push new key and value in existing object array

和自甴很熟 提交于 2019-11-27 14:50:32

问题


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".

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:


array_push() doesn't allow you to specify keys, only values: 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:


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

Check this comment on the array_push manual page.



来源:https://stackoverflow.com/questions/23916521/php-push-new-key-and-value-in-existing-object-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!