0

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?

1

2 Answers 2

1

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++;
}
Sign up to request clarification or add additional context in comments.

Comments

0
$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.

3 Comments

That gives: 0->3 1->2 2->1 3->0 4->4 5->3 6->2 7->1 8->5 9->4
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.
That works but only if there is a total number of images that is a multiple of 4. Close ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.