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?
-
this seems to answer your questions quite well stackoverflow.com/questions/1316916/…Prix– Prix2010年08月02日 19:17:15 +00:00Commented Aug 2, 2010 at 19:17
2 Answers 2
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++;
}
Comments
$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.