nac20 Posted October 16, 2008 Share Posted October 16, 2008 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 ) ) Quote Link to comment https://forums.phpfreaks.com/topic/128694-array-sort/ Share on other sites More sharing options...
MadTechie Posted October 16, 2008 Share Posted October 16, 2008 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>"; ?> Quote Link to comment https://forums.phpfreaks.com/topic/128694-array-sort/#findComment-666966 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.