我从对象方法返回一个值并将其放入数组中。代码如下:
$additionalTestConfirmation = array();
$additionalTests = $this->getAdditionalTestsSelected();
foreach($additionalTests as $availableTest)
{
$additionalTestConfirmation = $availableTest->getName();
}
$appointment = $this->getAppointment();
$tokens = array(
'%DATE%' => $this->getAppointment()->getDate(),
'%LOCATION%' => $this->getAppointment()->getLocation(),
'%TIME%' => $this->getTime(),
'%ROOM%' => $this->getRoom(),
'%NAME%' => ($this->getUser() ? $this->getUser()->getFullName() : null),
'%TZ%' => $this->getAppointment()->getShowTimeZone() ? $this->getAppointment()->getTimeZone() : '',
'%AdditionalTestsSelected%' => $additionalTestConfirmation,
);
对于上面的代码,我收到一条系统错误消息:注意:/ Users / alexhu / NetBeansProjects / menagerie / svn / trunk / apps / frontend / modules / legacy / legacy_lib / lib / classes / AppointmentTime中的数组到字符串转换第379行.php。 如何避免这种情况并获得我想要的$ availableTest-> getName()返回值。感谢
答案 0 :(得分:0)
foreach($additionalTests as $availableTest)
{
$additionalTestConfirmation[] = $availableTest->getName();
}
在您发表评论后,我建议您:
$appointment = $this->getAppointment();
$token = array(
'%DATE%' => $appointment->getDate(),
'%LOCATION%' => $appointment->getLocation(),
'%TIME%' => $this->getTime(),
'%ROOM%' => $this->getRoom(),
'%NAME%' => ($this->getUser() ? $this->getUser()->getFullName() : null),
'%TZ%' => $appointment->getShowTimeZone() ? $appointment->getTimeZone() : ''
);
$tokens = array();
$additionalTests = $this->getAdditionalTestsSelected();
foreach($additionalTests as $availableTest)
{
$token['%AdditionalTestsSelected%'] = $availableTest->getName();
$tokens[] = $token;
}
// here comes logic for all tokens
答案 1 :(得分:0)
为了将每个$ availableTest-> getName()添加到数组$ additionalTestConfirmation,您需要在数组和赋值运算符[]
上使用=
foreach($additionalTests as $availableTest)
{
$additionalTestConfirmation[] = $availableTest->getName();
}
您还可以使用array_push
功能答案 2 :(得分:0)
将元素分配给数组时,必须指定索引,或使用空方括号([]
)添加项目:
foreach($additionalTests as $availableTest) {
$additionalTestConfirmation[] = $availableTest->getName();
// or array_push($additionalTestConfirmation, $availableTest->getName());
// see: http://us3.php.net/array_push
}
有关详情,请参阅文档:http://php.net/manual/en/language.types.array.php
修改强>
另外,在这一行:
'%AdditionalTestsSelected%' => $additionalTestConfirmation,
...您正在将数组传递给此索引。如果代码后缀预期这是一个字符串,则可能导致错误。 * 这不会导致错误 - 将数组放入另一个数组是完全可以接受的。正如我所提到的,它实际上取决于使用$tokens
数组的代码将执行和期望的内容。如果它需要AdditionalTestsSelected
索引的纯字符串,则可能需要执行以下操作:
'%AdditionalTestsSelected%' => implode(',', $additionalTestConfirmation)
...使值成为逗号分隔列表。
另请注意,在该行的末尾您还有一个额外的逗号。