Trying to sort an array of objects using usort in php

Matt Anderson

I'm working on a WordPress site, trying to sort post tags, which is an array of objects with various members including slug and name. I've created an array of tag slug strings in priority order, and trying to sort a post's array of tags according to that array's values, with the post's slug as the key. Example:

$tagPriorityMap = array(
  "research" => 0,
  "strategy" => 1,
  "naming" => 2,
  "identity" => 3,
  "packaging" => 4,
  "environment" => 5,
  "digital" => 6,
);
function sort_tags($a, $b) {
  if ($tagPriorityMap[$a->slug] == $tagPriorityMap[$b->slug]) {
    return 0;
  }
  return ($tagPriorityMap[$a->slug] < $tagPriorityMap[$b->slug]) ? -1 : 1;
}

If I echo some code inside the sort_tags function, it shows that $a->slug is a string like "strategy", but it also shows that $tagPriorityMap[$a->slug] returns no value. What am I doing wrong? Thanks.

Ruben

your $tagPriorityMap must be declared as a global variable inside the function. Jut try:

function sort_tags($a, $b) {
  global $tagPriorityMap;
  if ($tagPriorityMap[$a->slug] == $tagPriorityMap[$b->slug]) {
    return 0;
  }
  return ($tagPriorityMap[$a->slug] < $tagPriorityMap[$b->slug]) ? -1 : 1;
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Using a variable to sort multidimensional php array (usort)

Sort an associative array in PHP using usort

Sort Array PHP usort

using usort on array of objects

Sorting an array using PHP's usort method

PHP Sorting Array Using usort() Not Working

Usort on Array of DateTime Objects in PHP - No Error, Array Not Sorting

Trying to sort a Java array of objects

PHP usort 2 dimensional array not working (sort by integer)

How can I sort a merged array using usort?

usort() Multidimensional array with PHP

Sort array by specific value with usort

Using usort to sort json output

Program termination when trying to sort an array of objects

Trying to sort an array of objects but splice is not a function?

NullPointerException when trying to sort array of objects

Using a selection sort to sort an array of objects?

Trying to output 2 objects from an array using a sort-object on one of them

Try to create basic function to sort array with usort

Usort sort multidimensional array by continuing values

Using usort on a php object not working

PHP : using Usort() inside a Loop

PHP custom sort function of multidimensional array because of usort members equality problem

How can i sort a multi-dimensional array by it's keys in one of it's elements with usort in php?

PHP: Sorting letters using usort or sort from an UTF-8 string causes unknown characters

Javascript sort array of objects using array of priority

Sort fixed array of objects by using another array

PHP - trying to sort an array by a numeric field

PHP array of objects - trying to extract key