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 ();
//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);
EDIT: After reading comments, checking out other threads that were valuable like this one: Sort multidimensional array by multiple keys and ignoring the PHP docs here: http://php.net/manual/en/function.array-multisort.php
I got my code working by using the array of indices by which array_multisort () sorts is the FIRST array provided. Again, the first argument passed to array_multisort() IS SORTED BY rather than the array you want sorted. This is contrary to the PHP docs but seems to work. If you find a misinterpretation or mistake in my code for why it is working, please let me know. Until then, the fix for my code ended up being this:
array_multisort($date_sort, SORT_DESC, $json_content);
It seems to sort $date_sort by descending order placing newest dates first and then sort the second array of objects by how the the first was sorted. I got the idea thinking of how programs like Excel would sort a table based on a single column.
Thank you for taking the time to give me feedback and ask questions. All of it was helpful in eventually figuring out the wording of the docs seemed opposite (as the array that is sorted-by is itself sorted too (of course), but that is not the intention of calling the function and it is the other arrays that are themselves sorted relative to the first array).