Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.