问题
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