我用过
unset($quotes_array[0]['methods'][0]);
$quotes_array[0]['methods'] = array_values($quotes_array[0]['methods']);删除数组的第一个元素,但使用该数组的选择窗体不再正确响应用户选择的单选按钮。原始数组如下所示:
Array
(
[0] => Array
(
[id] => advshipper
[methods] => Array
(
[0] => Array
(
[id] => 1-0-0
[title] => Trade Shipping
[cost] => 20
[icon] =>
[shipping_ts] =>
[quote_i] => 0
)
[1] => Array
(
[id] => 2-0-0
[title] => 1-2 working days
[cost] => 3.2916666666667
[icon] =>
[shipping_ts] =>
[quote_i] => 1
)
[2] => Array
(
[id] => 4-0-0
[title] => 2-3 working days
[cost] => 2.4916666666667
[icon] =>
[shipping_ts] =>
[quote_i] => 2
)
[3] => Array
(
[id] => 8-0-0
[title] => Click & Collect
[cost] => 0
[icon] =>
[shipping_ts] =>
[quote_i] => 3
)
)
[module] => Shipping
[tax] => 20
)
)修改后的数组如下所示:
Array
(
[0] => Array
(
[id] => advshipper
[methods] => Array
(
[0] => Array
(
[id] => 2-0-0
[title] => 1-2 working days
[cost] => 3.2916666666667
[icon] =>
[shipping_ts] =>
[quote_i] => 1
)
[1] => Array
(
[id] => 4-0-0
[title] => 2-3 working days
[cost] => 2.4916666666667
[icon] =>
[shipping_ts] =>
[quote_i] => 2
)
[2] => Array
(
[id] => 8-0-0
[title] => Click & Collect
[cost] => 0
[icon] =>
[shipping_ts] =>
[quote_i] => 3
)
)
[module] => Shipping
[tax] => 20
)
)我怀疑这个问题是因为在修改后的数组中,quote_i现在从1开始,而不是原来的0。所以我的quote_i是1,2然后是3,但是它应该是0,1,然后是2。
我尝试过使用array_walk来纠正这个问题,但是没有成功。
有什么建议可以解决这个问题吗?
发布于 2013-05-03 18:07:41
技巧基本上是纠正quote_i
$counter = 0;
foreach ($quotes_array[0]['methods'] as $key => $value)
{
$quotes_array[0]['methods'][$key]['quote_i'] = $counter;
$counter++;
}发布于 2013-05-03 18:11:31
使用与您的用例相匹配的示例代码的array_walk
<?php
foreach ($quotes_array[0]['methods'] as $a) {
$a = array(
array('quote_i' => 1),
array('quote_i' => 2),
array('quote_i' => 3)
);
array_walk($a, function(&$item, $key) {
$item['quote_i'] = $item['quote_i'] - 1;
});
var_dump($a);
// array([0] => array('quote_i' => 0), [1] => array('quote_i' => 1), [2] => array('quote_id' => 2))
}https://stackoverflow.com/questions/16356301
复制相似问题