【发布时间】:2012-02-16 23:09:47
【问题描述】:
我正在尝试从 PHP 中的对象构建一个数组。我只想要对象的某些属性,但我不知道每次它们会是什么。我需要的属性名称存储在一个数组中。以下是我的代码目前的工作方式:
// Hard-coded attributes 'colour' and 'size'
while ($objVariants->next())
{
$arrVariants[] = array
(
'pid' => $objVariants->pid,
'size' => $objVariants->size,
'colour' => $objVariants->colour,
'price' => $objVariants->price
);
}
我想使用变量而不是硬编码属性(颜色和大小),这是因为它可能并不总是颜色和大小,具体取决于用户在 CMS 中设置的内容。例如:
$arrVariantAttr = $this->getVariantAttr(); // Get the names of the custom variants and put them in an array e.g colour, size
while ($objVariants->next())
{
$arrVariants[] = array
(
'pid' => $objVariants->pid,
foreach($arrVariantAttr as $attr)
{
$attr['name'] => $objVariants-> . $attr['name']; // Get each variant out of the object and put into an array
}
'price' => $objVariants->price
);
}
上面的代码不起作用,但希望它说明了我正在尝试做的事情。任何帮助将不胜感激,谢谢!
【问题讨论】: