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

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

本文介绍了PHP 在现有对象数组中推送新的键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在研究对象和数组如何使用 PHP 时,我遇到了一个新问题.在现有问题中搜索并没有给我自己正确的推动".

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

我有这个例子:

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

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

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

推荐答案

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

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

这篇关于PHP 在现有对象数组中推送新的键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 14:07