我想为每个对象添加新属性。我的代码如下所示:
function getCitationDataofquotes($var1){
$query = "SELECT `id`,`title`,`source`,`content`,`page`,`city`,`publisher` FROM `#__gpo_citations_quotes`";
$query .= " WHERE `id`='" . $var1 . "'";
if (!empty($query))
{
$some= array();
$this->_db->setQuery($query);
$data = $this->_db->loadObject();
return $data;
}
$value = $datapages->getCitationDataofquotes($var1);
$getdataofcitation['citations'][] = $value;
然后我的输出返回数据如下
{id: "12091",
title: "Homicide Victims by Year and Jurisdiction, 1989–90 to 2010–12",
source: "Homicide in Australia: 2010–11 to 2011–12: National Homicide Monitoring Program report",
content: " ACT = Australian Capital Territory]",
page: "p. 37",
city: "Canberra",
publisher: "Australian Institute of Criminology"
},
{
id: "8901",
title: "test",
source: null,
content: "",
page: null,
city: null,
publisher: null
},
现在我想为每个对象添加新属性。我希望每个对象都有这个输出。
{ id: "8901",
title: "test",
source: null,
content: "",
page: null,
city: null,
publisher: null ,
**new property: something**}
首先,您的$查询容易受到Sql注入攻击。 BTW有多种方法可以达到你想要的效果。例如,您可以在查询中添加属性:
SELECT 'some value' As `some_field` ...
如果你想在php代码中添加它,你可以像@madalinivascu上面说的那样动态添加它:
如果它是一个对象:
$myObject->myNewProperty = 'My new value';
# if it is dynamically and you don't know the name ...
$myObject->{"myNewProperty"} = 'My new value';
如果是数组:
$myArray['myNewProperty'] = 'My new value';
当带有多个带数组的对象返回值时更新此代码
$value[] = $datapages->getCitationDataofquotes($var1);
for($i=0; $i<count($value); $i++)
{
$value[$i]->newprop = 'new content';
}