我总是很难理解这些foreach数组的东西,SO是一个非常有价值的资源,所以我希望你们能帮助我解决这个问题。
public function progress_bar()
{
$items = array(
array(
'step-name' => 'Setup',
'url' => '/projects/new/setup/',
),
array(
'step-name' => 'Artwork',
'url' => '/projects/new/artwork/',
),
array(
'step-name' => 'Review',
'url' => '/projects/new/review/',
),
array(
'step-name' => 'Shipping',
'url' => '/projects/new/shipping-info/',
),
array(
'step-name' => 'Billing',
'url' => '/projects/new/billing/',
),
array(
'step-name' => 'Receipt',
'url' => '/projects/new/receipt/',
),
);
// Status can be active, editing, or complete.
foreach ($this->progress as $step => $status)
{
foreach ($items as $item)
{
$item['step-name'] == ucfirst($step) ? $item['status'] = $status : '';
}
}
return $items;
}
$this->progress
包含状态数组('setup' => 'active', 'artwork' => 'editing')
我想在$items
数组中添加$this->progress
中每个匹配项的状态
$items = array(
array(
'step-name' => 'Setup',
'url' => '/projects/new/setup',
'status' => 'active',
),
etc...
);
如果我正确理解你的问题,问题是你试图将数组元素添加到$items,但你实际做的是将元素添加到一个临时变量($item),它不引用原始的$items变量。
我建议这样处理:
foreach ($this->progress as $step => $status)
{
// Having the $key here allows us to reference the
// original $items variable.
foreach ($items as $key => $item)
{
if ($item['step-name'] == ucfirst($step) )
{
$items[$key]['status'] = $status;
}
}
}
return $items;
您是否被锁定为使用数组来存储$items?如果是这样,您将陷入嵌套循环("对于$this->progress中的每个元素,检查$items中的每个元素。如果匹配,更新$items"或类似的东西)。如果您有一定的灵活性,我将对$items (php术语中的关联数组)使用散列,其中索引是步骤名称。所以$items['Setup']将包含'url' =>…'status' =>…等。明白了吗?然后你的算法分解为"对于$this->progress中的每个元素,通过名称($items[$step_name])获取$items中的元素并更新它的信息。"
我会改变$items数组键的方式,并像这样做。阻止使用嵌套循环。
public function progress_bar()
{
$items = array(
'Setup' => array(
'url' => '/projects/new/setup/',
),
'Artwork' => array(
'url' => '/projects/new/artwork/',
),
'Review' => array(
'url' => '/projects/new/review/',
),
'Shipping' => array(
'url' => '/projects/new/shipping-info/',
),
'Billing' => array(
'url' => '/projects/new/billing/',
),
'Receipt' => array(
'url' => '/projects/new/receipt/',
)
);
// Status can be active, editing, or complete.
foreach ($this->progress as $step => $status)
{
$item[ucfirst($step)]['status'] = $status;
}
return $items;
}