php


How do I sort an array of objects in PHP?


I'm struggling to get array_multisort() working. I'm sorting some data retrieved from JSON that is an array of five objects, each with data for blog posts in this format:
"1":{"title": "It's a fixer-upper of a planet but we could make it work",
"post_date": "1454889600",
"author": "Elon Musk",
"content": "<p>We choose to go to the moon in this decade and do the other things...</p>",
"category": [ "mars", "space travel" ] },
"2":{"title": "Failure is not an option",
"post_date": "1456099200",
"author": "Gene Kranz",
"content": "<p>Dinosaurs are extinct today because ...</p>",
"category": [ "mis-quoted", "apollo 13" ] },
...etc
I get the file in PHP, decode the JSON into an associative array and then create an array of human readable dates which I have working. I have an array of five objects and need to sort the array by said dates. I then try to use array_multisort and cannot seem to find a syntax that work. Any help would be appreciated and I'm sure it's something small I'm over-looking. No matter how hard I google, I just can't seem to get the search string right. Help please?
<?php //This part I'm confident is working.
$json = file_get_contents("./data/posts.json");
$json_content = json_decode($json, true);
$date_sort = array ();
$posts = array ();
//Sorting the Array - this part seems to work
foreach ($json_content as $postObj) {
$post_date_human = date ('Y-m-d', $postObj['post_date']);
array_push($date_sort, $post_date_human);
}
print_r ($date_sort); //Seems to be working fine, now to try to sort one array of objects by the position of dates in the second array
// Wai u no werk!?
array_multisort($json_content, $date_sort = SORT_ASC);
print_r ($json_content);
For Reference See Below Code.
$json_content = msort($json_content, "post_date");
And here's the function itself:
/**
* Sort a 2 dimensional array based on 1 or more indexes.
*
* msort() can be used to sort a rowset like array on one or more
* 'headers' (keys in the 2th array).
*
* #param array $array The array to sort.
* #param string|array $key The index(es) to sort the array on.
* #param int $sort_flags The optional parameter to modify the sorting
* behavior. This parameter does not work when
* supplying an array in the $key parameter.
*
* #return array The sorted array.
*/
function msort($array, $key, $sort_flags = SORT_REGULAR) {
if (is_array($array) && count($array) > 0) {
if (!empty($key)) {
$mapping = array();
foreach ($array as $k => $v) {
$sort_key = '';
if (!is_array($key)) {
$sort_key = $v[$key];
} else {
// #TODO This should be fixed, now it will be sorted as string
foreach ($key as $key_key) {
$sort_key .= $v[$key_key];
}
$sort_flags = SORT_STRING;
}
$mapping[$k] = $sort_key;
}
asort($mapping, $sort_flags);
$sorted = array();
foreach ($mapping as $k => $v) {
$sorted[] = $array[$k];
}
return $sorted;
}
}
return $array;
}
For More information Visit: https://blog.jachim.be/2009/09/php-msort-multidimensional-array-sort/comment-page-1/
Take a hint from this two links:
I think it have nice solution
link1 , link2
Please read doc for multisort, You will get better idea about solve your errors

Related Links

Cakephp 2 using post data can't login properly
Php Arrays Group and Sum [closed]
Not able to access mysql server using workbench on local network connection
Live php Error logs on Windows
php ssh password on server
How to avoid putting a file name in post data?
remove woocommerce link when cart is empty
Codeigniter - Default template's PHP code is not executed
How combine the data connected by a linking/associate table into one column of a query?
checkbox not from php form updating mysql
How to update data after insert? [closed]
PHP: Parsing data within multidimensional array
PHP cURL - thread safe?
Function in PHP is not working [closed]
data is not stored in database when follow button is pressed
filtering word digit from number and blocking them

Categories

HOME
orientdb
macos-sierra
apple-push-notifications
facebook-messenger
antd
devexpress
dry
ews
mathematical-optimization
ontology
turbojpeg
ipv6
bittorrent
onvif
xamarin-zebble
parsley.js
sap-fiori
rangy
documentum
jquery-file-upload
jodatime
corona
psql
bazaar
neo4j.rb
ini
animated-gif
function-points
fusetools
macromedia
sendmessage
amazon-cloudtrail
fusion
social-networking
xenapp
winsock
cucumber-junit
microsoft-certifications
om-next
gsp
dreamfactory
jade4j
aurelia-cli
aurelia-http-client
sbjson
access-denied
daz3d
axis
.net-micro-framework
ol3-google-maps
photoswipe
knockout-2.0
embedded-v8
simple-schema
winmerge
glassfish-4.1
apache-modules
decoder
node-glob
strpos
frame-grab
gulp-uglify
gwt-syncproxy
diawi
phpquery
smart-tv
place
chicagoboss
wlanapi
search-form
cache-manifest
abstract-factory
dbmigrate
text-align
nesper
dmake
cpu-time
iosched
lsa
proxy-server
pbkdf2
apache-shindig
coalesce
blobstorage
semantic-merge
zend-pdf
workflow-manager-1.x
microblogging
vows
firefly-mv
asp.net-mvc-views
eaccelerator
wmd-editor
inversion
rendering-engine
synthesizer

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App