tags:

views:

53

answers:

2

In a multidimensional array, each array has a field 'order'. I need to change this value as follows:

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

etc...

Ill be doing this while iterating through the array as follows

$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['order'] contains the original order value (left column in the first code snippet, coming out of the DB ASC) and should be changed to the corresponding number in the right column.

So basically, the value needs to be changed to the reverse order, while looking at each set of numbers in blocks of 4. I will not know what the highest order number will be, it will increase as new images are added.

What's the best way to do this using the above foreach?

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

and then some correction for the last block...

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

Of course re-mapping with an additional array works fine, but you still need to generate the map somehow.

maschka
That gives:0->31->22->13->04->45->36->27->18->59->4
stef
Sorry, this edited version gives the result from your textual description. It doesn't match your example for 8 and 9 though. Not sure which way you wanted it.
maschka
That works but only if there is a total number of images that is a multiple of 4. Close ...
stef
+1  A: 

Just re-map it

$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++;
}
Peter Bailey
Perfect, very simple solution. Many thanks.
stef