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

Fetch PHP SOAP request data
Codeigniter user guide - why do they assign CI object by reference and say that it's important
Exclude a year from MYSQL query
Change .htaccess to work ?_escaped_fragment_= URL
Get all text within parent node with xpath
Count amount of items with the same value in the table
wp_enqueue_script() no longer working in my function.php file
PHP mail has empty body under certain conditions
PHP: Don't echo a variable in a while loop IF it's a duplicate
Laravel - Counting from third relationship
Duplicate table entry error
Get parameters from URL in Controller Symfony2
Laravel 4 Undefined variable errors
How to Convert this to a ternary operator
404 error laravel 4 routing
PHP Restrict access unless logged in

Categories

HOME
php
windows-8.1
add-on
mousemove
subdomain
dafny
vsts-build
android-emulator
mathematical-optimization
cdi
kurento
tup
bellman-ford
stack-overflow
driver
yeoman-generator-angular
phpstorm-2017.1
vimeo
significance
akka-persistence
hdl
web-analytics
uislider
vuforia
managed-c++
tortoisemerge
fstar
xdebug
msdeploy
sendmessage
sca
bootstrap-sass
db2-luw
runtimeexception
fastlane
widestring
task-parallel-library
game-center
jacoco-maven-plugin
uipickerview
minikube
vesta
nuclio
flume-twitter
autorelease
libreoffice-writer
android-5.0-lollipop
non-linear-regression
comm
spring.net
apache-modules
gmaps.js
mechanicalturk
dymola
kendo-treeview
scheduledexecutorservice
right-to-left
adp
android-syncadapter
accessibilityservice
gridbaglayout
gwt-syncproxy
gdl
bjam
sqlbase
libz
ngcordova
android-handler
ipod
scala-macros
fiware-bosun
device-admin
adwords-apiv201402
window-resize
jquery-mobile-flipswitch
osascript
box2dweb
neo4jphp
sql-function
gpu-programming
jomsocial
proc-open
ip-geolocation
sfinae
viewpagerindicator
sigar
mmc3
grails-validation
django-pagination
3-tier
bucket
html-generation

Resources

Encrypt Message