Jump to content

Array sort


nac20

Recommended Posts

Hi,

 

I have a multi-dimensional array (called $categories) which is not sorting as I'd like, please can someone show me the correct statement to sort the nested array in cat_name order (example contents below).

I'm guessing I have to use array_multisort but can't get it working.

 

Thanks in advance,

 

Alan

 

 

Array ( [0] => Array ( [cat_parent_id] => 0 [cat_id] => 19 [cat_image] => 4754bded7e4b19603e571feeecb32fcc.jpg [cat_name] => Product A [cat_description] => Product description ) [1] => Array ( [cat_id] => 31 [cat_parent_id] => 19 [cat_name] => Product B [cat_image] => [cat_description] => adult )  )

Link to comment
https://forums.phpfreaks.com/topic/128694-array-sort/
Share on other sites

Try this here is an example

 

<?php
function cmp($a, $b)
{
    return strcmp($a["cat_name"], $b["cat_name"]);
}

$data = array();
$data[] = Array ( "cat_parent_id" => 0,  "cat_id" => 19, "cat_image" => "4754bded7e4b19603e571feeecb32fcc.jpg", "cat_name" => "Product A", "cat_description" => "Product description" );
$data[] = Array ( "cat_parent_id" => 19,  "cat_id" => 31, "cat_image" => "", "cat_name" => "Product B", "cat_description" => "Adult" );
$data[] = Array ( "cat_parent_id" => 19,  "cat_id" => 31, "cat_image" => "", "cat_name" => "Product R", "cat_description" => "Adult" );
$data[] = Array ( "cat_parent_id" => 19,  "cat_id" => 31, "cat_image" => "", "cat_name" => "Product E", "cat_description" => "Adult" );
$data[] = Array ( "cat_parent_id" => 19,  "cat_id" => 31, "cat_image" => "", "cat_name" => "Product A", "cat_description" => "Adult" );
$data[] = Array ( "cat_parent_id" => 19,  "cat_id" => 31, "cat_image" => "", "cat_name" => "Product D", "cat_description" => "Adult" );

echo "Org List:<br><pre>";
foreach($data as $D)
{
echo $D['cat_name']."<br>";
}
echo "<\pre>";
usort($data, "cmp");

echo "New List:<br><pre>";
foreach($data as $D)
{
echo $D['cat_name']."<br>";
}
echo "<\pre>";
?>

Link to comment
https://forums.phpfreaks.com/topic/128694-array-sort/#findComment-666966
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.