0

I would like to sort only the "Name" value on a table but it doesn't seem to work.

$fruits = array(
      array(
        'image' => '<img class="img" src="papaya.jpg">',
        'name' => 'Papaya',
        'description'=> 'Color: Yellow',
      ),

  array(
    'image' => '<img class="img" src="blueberry.jpg">',
    'name' => 'Blueberry',
    'description'=> 'Color: Blue',
  ),

  array(
    'image' => '<img class="img" src="orange.jpg">',
    'name' => 'Orange',
    'description'=> 'Color: Orange',
  ),
);
array_multisort($fruits['name'], SORT_ASC);

I wanted the output to be like this:

Image Name Description
pic Blueberry Color: Blue
pic Orange Color: Orange
pic Papaya Color: Yellow
1
  • 1
    Have you tried using usort with a custom callback? Commented Feb 18, 2021 at 4:07

1 Answer 1

1

Try to use usort function with appropriate callback function. You can do it like this.

$fruits = array(
    array(
        'image' => '<img class="img" src="papaya.jpg">',
        'name' => 'Papaya',
        'description' => 'Color: Yellow',
    ),

    array(
        'image' => '<img class="img" src="blueberry.jpg">',
        'name' => 'Blueberry',
        'description' => 'Color: Blue',
    ),

    array(
        'image' => '<img class="img" src="orange.jpg">',
        'name' => 'Orange',
        'description' => 'Color: Orange',
    ),
);

function cmp($a, $b)
{
    return strcmp($a["name"], $b["name"]);
}


usort($fruits, "cmp");
Sign up to request clarification or add additional context in comments.

1 Comment

saved me a lot of time figuring it out. thank you so much! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.