views:

40

answers:

2

I have a multi-dimensional array right now that looks like this:

function art_appreciation_feeds() {
 $items = array(
  array('site' => '', 'uri' => '', 'feed' => ''),
  array('site' => '', 'uri' => '', 'feed' => ''),
  array('site' => '', 'uri' => '', 'feed' => ''),
  array('site' => '', 'uri' => '', 'feed' => ''),
 );
 return $items; 
}

Right, so I output the values of the array using this function:

foreach($items as $i => $row) {

What I'm looking to do, is add another value to that array called category so that I'd have:

array(
  array('site' => '', 'uri' => '', 'feed' => '', 'category' => ''),
);

And when I'm going through the loop above, to output it in order by the category field with a <h2>Category</h2> at the top only of each section.

Is that the best way to do this and if so, how would I change my loop to accommodate that? Caveat: I can change the array as well if you think something else is better.

Thanks!

+2  A: 

I am sure there are better ways to go about it and not sure if this is easy to do in your situation, but just a suggestion. Why not have the category as an array key and inserting all the records relevant to that category as sub array?

for instance:

$items['catname1'][] = array('site' => '', 'uri' => '', 'feed' => '');
$items['catname2'][] = array('site' => '', 'uri' => '', 'feed' => '');
$items['catname1'][] = array('site' => '', 'uri' => '', 'feed' => '');

and then sorting based on the array key?

Or if you dont want to add that extra layer. Add a counter value to catname and store the catname in the sub array itself like

$items['catname1'.$c] = array('site' => '', 'uri' => '', 'feed' => '', cat=>'catname1');
$items['catname2'.$c] = array('site' => '', 'uri' => '', 'feed' => '', cat=>'catname2');
$items['catname1'.$c] = array('site' => '', 'uri' => '', 'feed' => '', cat=>'catname1');

using ksort() you should be able to sort on the array key easily.

Sabeen Malik
A: 

One way is using usort(), which allows you to specify a sort function:

function compareTwoItems($a, $b)
{
   return strcmp($a["category"], $b["category"]);
}

usort($items, "compareTwoItems");

Once usort() is done, the items are sorted, with all items of the same category being adjacent in the array.

If you want, you can continue to fine-tune your compareTwoItems() function -- e.g. do sub-sorting within a category:

function compareTwoItems($a, $b)
{
    $strcmp = strcmp($a["category"], $b["category"]);
    if ($strcmp != 0)
        return $strcmp;
    else
        return strcmp($a["site"], $b["site"]);
}
Mike Morearty
Not that I'm the downvoter (it's a valid solution IMHO), but **DO** quote your array_keys! (Or I'm gonna drive-by-define `define('category','site');` just to spite the code :P )
Wrikken
Okay, I quoted the array keys.
Mike Morearty