开发者

PHP number processing

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 -开发者_JAVA技巧> 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?


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++;
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜