2010-08-02 42 views
0

在多維數組中,每個數組都有一個'order'字段。我需要改變這個值,如下所示:PHP號碼處理

0 -> 3  
1 -> 2  
2 -> 1  
3 -> 0 
4 -> 7 
5 -> 6 
6 -> 5 
7 -> 4 
8 -> 9 
9 -> 8 

等等

生病是如下

$c = 0; 
     foreach($data['images'] as $i) 
     { 
      //$i['order'] contains the original order value 

      $processed_imgs[$c]['file'] = $i['file']; 
      $processed_imgs[$c]['text'] = $i['text']; 
      $processed_imgs[$c]['order'] = 'X';      
      $c++; 
     } 

$這樣做,同時通過遍歷數組I [ '秩序']包含原始訂單值(第一個代碼片段中的左列,從DB ASC出來),並且應該更改爲右列中的相應編號。

因此,基本上,需要將值改爲相反順序,同時以4個塊爲單位查看每組數字。我不知道最高順序號是多少,它會隨着新圖像的添加而增加。

使用上述foreach做這件事的最好方法是什麼?

+0

這似乎回答你的問題非常好http://stackoverflow.com/questions/1316916/php-function-to-reorder-an-array – Prix 2010-08-02 19:17:15

回答

1

只是重新映射它

$orderMap = array(3, 2, 1, 0, 7, 6, 5, 4, 9, 8); 

$c = 0; 
foreach($data['images'] as $i) 
{ 
    //$i['order'] contains the original order value 

    $processed_imgs[$c]['file'] = $i['file']; 
    $processed_imgs[$c]['text'] = $i['text']; 
    $processed_imgs[$c]['order'] = $orderMap[$i['order']];      
    $c++; 
} 
+0

完美的,非常簡單的解決方案。非常感謝。 – stef 2010-08-02 19:32:26

0
$processed_imgs[$c]['order'] = floor($i['order']/4)*4 + 3-$i['order'] % 4; 

,然後一些修正的最後一塊...

if (count($data['images'])-1-$i['order'] < count($data['images'])%4) { 
    $processed_imgs[$c]['order'] -= 4-count($data['images'])%4; 
} 

與其它陣列當然重映射工作正常,但你仍然需要以某種方式生成地圖。

+0

這給: 0-> 3 1-> 2 2-> 1 3-> 0 4-> 4 5-> 3 6-> 2 7-> 1 8-> 5 9-> 4 – stef 2010-08-02 19:17:38

+0

對不起,這個編輯版本給出了你的文字說明的結果。但它與8和9的例子不符。不知道你想要它的方式。 – maschka 2010-08-02 19:23:11

+0

這是有效的,但只有當圖像的總數是4的倍數時纔有效。關閉... – stef 2010-08-02 19:25:45