开发者

Sorting a 2 dimensional array in PHP

wonder if anyone can help;

I have an a two dimensional array which I need to group by any common "job number" element; Here's an example - I'm just playing with the idea at the moment, The $i is just a counter that iterates through the array results;

$galleryItems[开发者_开发技巧$i][0] = 'example title';//the title
 $galleryItems[$i][1] = 'example description';//description
 $galleryItems[$i][2] = 'the client';//client
 $galleryItems[$i][3] = '00000';//job number

Any ideas on how to group these toegther, eg so if had a number of 00000 job items it would stick all these toegther, and any 00001 would be group together etc.

Thanks


$galleryItemsGrouped = array();
foreach($galleryItems as $k => $v) {
  $galleryItemsGrouped[$v[3]][] = $v;
}
var_dump($galleryItemsGrouped);

or maybe that's what you mean

usort($galleryItems, function($a,$b) {
  if($a[3] == $b[3]) return 0;
  return $a[3]<$b[3] ? -1 : 1;
});
var_dump($galleryItems);


to stick together you have to use php's implode function on $galleryItems[$i]


I think you'll probably have to write a sorting callback function that you can use with usort(): http://php.net/manual/en/function.usort.php

If this data comes from a database, you might want to look at using a GROUP BY clause there and save yourself the trouble of sorting on the server.

On a more designy level, perhaps consider an array of galleryItem objects instead of a 2D array.

G


Instead of number indexes, use names:

$galleryItems[$i]['title'] = 'example title';//the title
$galleryItems[$i]['description'] = 'example description';//description
$galleryItems[$i]['client'] = 'the client';//client
$galleryItems[$i]['job_number'] = '00000';//job number

Then you can sort with this function:

function sort_by_job_number ( $a, $b ) 
{
    if ( $a['job_number'] == $b['job_number'] ) {
        return 0;
    }    

    return ($a['job_number'] > $b['job_number']) ? 1 : -1;
}

usort($galleryItems,'sort_by_job_number');

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜