Skip to content
Fix Code Error

How to Sort Multi-dimensional Array by Value?

March 13, 2021 by Code Error
Posted By: Anonymous

How can I sort this array by the value of the “order” key? Even though the values are currently sequential, they will not always be.

Array
(
    [0] => Array
        (
            [hashtag] => a7e87329b5eab8578f4f1098a152d6f4
            [title] => Flower
            [order] => 3
        )

    [1] => Array
        (
            [hashtag] => b24ce0cd392a5b0b8dedc66c25213594
            [title] => Free
            [order] => 2
        )

    [2] => Array
        (
            [hashtag] => e7d31fc0602fb2ede144d18cdffd816b
            [title] => Ready
            [order] => 1
        )
)

Solution

Try a usort, If you are still on PHP 5.2 or earlier, you’ll have to define a sorting function first:

function sortByOrder($a, $b) {
    return $a['order'] - $b['order'];
}

usort($myArray, 'sortByOrder');

Starting in PHP 5.3, you can use an anonymous function:

usort($myArray, function($a, $b) {
    return $a['order'] - $b['order'];
});

And finally with PHP 7 you can use the spaceship operator:

usort($myArray, function($a, $b) {
    return $a['order'] <=> $b['order'];
});

To extend this to multi-dimensional sorting, reference the second/third sorting elements if the first is zero – best explained below. You can also use this for sorting on sub-elements.

usort($myArray, function($a, $b) {
    $retval = $a['order'] <=> $b['order'];
    if ($retval == 0) {
        $retval = $a['suborder'] <=> $b['suborder'];
        if ($retval == 0) {
            $retval = $a['details']['subsuborder'] <=> $b['details']['subsuborder'];
        }
    }
    return $retval;
});

If you need to retain key associations, use uasort() – see comparison of array sorting functions in the manual

Answered By: Anonymous

Related Articles

  • Reference — What does this symbol mean in PHP?
  • Where should I place my Vaadin 10+ static files?
  • How do I include certain conditions in SQL Count
  • sql query to find priority jobs
  • Reference - What does this regex mean?
  • Linking or Routing dynamicaly with Next.js
  • Sort array of objects by object fields
  • PHP parse/syntax errors; and how to solve them
  • How do I remove all null and empty string values…
  • getting error while updating Composer
  • lodash multi-column sortBy descending
  • Multi-dimensional sorting with variable amount of…
  • How does PHP 'foreach' actually work?
  • PHP Sort a multidimensional array by element containing date
  • Execute a PHP script from another PHP script
  • using 2-dimensional arrays is faster than two of…
  • What's the difference between utf8_general_ci and…
  • apache server reached MaxClients setting, consider…
  • Pure JavaScript equivalent of jQuery's $.ready() -…
  • Unexpected behaviour java priority queue. Object…
  • Grouping functions (tapply, by, aggregate) and the…
  • Javascript dynamic sorting array of object include…
  • Proper use of the IDisposable interface
  • "Notice: Undefined variable", "Notice: Undefined…
  • Sorting Backbone Collections
  • Trouble with qsort with key/value structs in a btree
  • How do I count unique visitors to my site?
  • Enumerating list after splitting - Python
  • How do you parse and process HTML/XML in PHP?
  • Smart way to truncate long strings
  • Creating an dynamic array, but getting segmentation…
  • Convert a PHP script into a stand-alone windows executable
  • Avoid creating new session on each axios request laravel
  • define() vs. const
  • problem with client server unix domain stream…
  • PHP - Failed to open stream : No such file or directory
  • How to bind v-for values to HTML attributes in Vue
  • MySQL 'Order By' - sorting alphanumeric correctly
  • How do I extract data from JSON with PHP?
  • Sort table rows In Bootstrap
  • How to concatenate two layers in keras?
  • C++ Need help sorting a 2D string array
  • How do malloc() and free() work?
  • What is stability in sorting algorithms and why is…
  • Why does C++ code for testing the Collatz conjecture…
  • How do I get currency exchange rates via an API such…
  • PHP Fatal error: Call to undefined function json_decode()
  • PHP7 : install ext-dom issue
  • Failed to authenticate on SMTP server error using gmail
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Vuejs sort and filter data
  • Htaccess: add/remove trailing slash from URL
  • Why is there no SortedList in Java?
  • Java Multidimensional array - how to create…
  • Memcached vs. Redis?
  • What are the undocumented features and limitations…
  • When dealing with Localizable.stringsdict, why…
  • C++11 introduced a standardized memory model. What…
  • Keras input explanation: input_shape, units,…
  • Laravel: PDOException: could not find driver
  • Rendering dynamically generated {{link-to}} links in…
  • Data not catching in multi step contact form
  • How can I enable the MySQLi extension in PHP 7?
  • C free(): invalid pointer
  • Saving image from PHP URL
  • How do you sign a Certificate Signing Request with…
  • Why is Google Firebase not recommended by Google -…
  • UTF-8 all the way through
  • Sorting a three-dimensional php array by…
  • How can I represent an 'Enum' in Python?
  • For-each over an array in JavaScript
  • C threads corrupting each other
  • Advice on Perl sort that uses Schwartzian transform
  • Difference between partition key, composite key and…
  • Remove similar tuple from dictionary of tuples
  • The mysql extension is deprecated and will be…
  • NSPhotoLibraryUsageDescription key must be present…
  • Secure hash and salt for PHP passwords
  • #define macro for debug printing in C?
  • PHP + JQuery - How to use these two together? Please…
  • PHP Error: Cannot use object of type stdClass as…
  • binary search tree is not working properly, but the…
  • How can I execute PHP code from the command line?
  • How to extract the hidden vector (the output of the…
  • How to filter a RecyclerView with a SearchView
  • EmberData: Two models related with hasMany relationships
  • Difference between implementation of network by…
  • Setting PHP tmp dir - PHP upload not working
  • setValue:forUndefinedKey: this class is not key…
  • BigQuery: user metadata described by start date and…
  • PHP-FPM and Nginx: 502 Bad Gateway
  • Are there any worse sorting algorithms than Bogosort…
  • Can't install laravel installer via composer
  • What is the difference between compare() and compareTo()?
  • Why would one omit the close tag?
  • What's the best way to get the last element of an…
  • How do I get the SQLSRV extension to work with PHP,…
  • Aurelia UX showcase app fails to load
  • React components not updating with state change
  • PHP code is not being executed, instead code shows…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How to change the author and committer name and e-mail of multiple commits in Git?

Next Post:

How do I delete a local repository in git?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error