我有一个数组,我需要修改它。下面你可以看到我的数组中的每个元素都有多个元素,其中一些元素也是数组。
Array
(
[ordered] => Array
(
[label] => Order ordered
[next_states] => Array
(
[deliver] => Array
(
[target] => delivered
)
)
[status] => complete
)
[delivered] => Array
(
[label] => Order delivered
[next_states] => Array
(
[check_invoice] => Array
(
[target] => invoice_correct
)
)
[status] => complete
)
[invoice_paid] => Array
(
[label] => Invoice paid
[next_states] =>
[status] => disabled
)
)
我需要做的是从我的主数组中的每个元素中取出元素[next_states]
并将其添加到下一个元素。实际上,我只需要keys
内的[next_states]
并将其添加到整个数组的下一个元素中的新键([next_step]
)。
实施例
Array
(
[ordered] => Array
(
[label] => Order ordered
[next_states] => Array
(
[deliver] => Array
(
[target] => delivered
)
)
[status] => complete
[next_step] => //This first one can remain empty because it's the first one.
)
[delivered] => Array
(
[label] => Order delivered
[next_states] => Array
(
[check_invoice] => Array
(
[target] => invoice_correct
)
)
[status] => complete
[next_step] => deliver // <- HERE
)
[invoice_paid] => Array
(
[label] => Invoice paid
[next_states] =>
[status] => disabled
[next_step] => check_invoice // <- HERE
)
)
我希望我的问题很清楚,有人会帮助我。我已经有一个foreach循环,我将[status]
添加到每个元素;
foreach ($steps as $key => $value) {
$steps[$key]['next_step'] = prev($steps);
if ($key === $nextStep) {
$steps[$key]['status'] = 'active';
} elseif (isset($uncompletedSteps[$key])) {
$steps[$key]['status'] = 'disabled';
} else {
$steps[$key]['status'] = 'complete';
}
}
我知道我必须在上面提到的foreach循环中添加一些东西,但我根本不知道如何做到这一点。有人可以告诉我该怎么做吗?
答案 0 :(得分:0)
使用array_keys创建用于在主数组中查找位置的数组:
$keys = array_keys($step);
// Test that array has more than one element
if (($klen = count($keys)) < 2 ) die("illegal lenth of the array");
for($i = 0; $i < $klen-1; $i++)
// Test that current element has next_states key
// and it points to array
if(isset($steps[$keys[$i]]['next_states']) && is_array($steps[$keys[$i]]['next_states']))
// Put key in next element
$steps[$keys[$i+1]]['next_step'] = key($steps[$keys[$i]]['next_states']);