2013-05-03 70 views
0

我使用修改阵列内容

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来更正此问题,但未成功。

对此解决方案有何建议?

+0

使用array_walk这是你在找什么? http://stackoverflow.com/questions/5217721/how-to-remove-array-element-and-then-re-index-array – Juampi 2013-05-03 10:08:13

回答

1

诀窍主要是纠正quote_i

$counter = 0; 
foreach ($quotes_array[0]['methods'] as $key => $value) 
{ 
    $quotes_array[0]['methods'][$key]['quote_i'] = $counter; 
    $counter++; 
} 
+0

完美的解决方案。这样做会纠正['quote_i'],但数组中还有很多。谢谢。另一天,我学到了新的东西。 – 2013-05-03 12:11:05

0

与示例代码应该符合你的使用情况

<?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)) 
}