PHP数字处理

PHP数字处理,php,Php,在多维数组中,每个数组都有一个字段“order”。我需要按如下方式更改此值: 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['o

在多维数组中,每个数组都有一个字段“order”。我需要按如下方式更改此值:

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['order']包含原始的order值(第一个代码段中的左列,来自DB ASC),应该更改为右列中的相应数字

因此,基本上,当以4块为单位查看每组数字时,需要将值更改为相反的顺序。我不知道最高订单号是多少,随着新图片的增加,订单号会增加

使用上述foreach的最佳方法是什么

$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;
}
if(计数($data['images'])-1-$i['order']
当然,使用附加数组重新映射可以很好地工作,但您仍然需要以某种方式生成映射。

只需重新映射即可

$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->31->22->13->04->45->36->27->18->59->4抱歉,这个编辑的版本给出了您文本描述的结果。但是,它与8和9的示例不匹配。不确定您想要哪种方式。这是可行的,但前提是图像总数是4的倍数。接近。。。