2013-05-03 112 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)) 
}