Solved

Sort Json array in php

Posted on 2010-11-08
3
1,211 Views
Last Modified: 2012-06-27
So say we have a json object

$json = '[{"date": "2011-08-07", "name": "bob"},{"date": "2011-07-07", "name": "jones"},{"date": "2011-09-03", "name": "blair"}]';

I can convert it over to an array

$arr = json_decode($json, true);

But i want to sort this by the date element so hypothetically if i did

foreach($arr as $thing)
{
echo ($thing['date']);
}

it would print by nearest event to furthest away
2011-07-07
2011-08-07
2011-09-03

whereas right now it would echo out like this:

2011-08-07
2011-07-07
2011-09-03
0
Comment
Question by:Brant Snow
3 Comments
 
LVL 6

Expert Comment

by:stilliard
ID: 34089285
0
 
LVL 8

Accepted Solution

by:
shanikawm earned 500 total points
ID: 34089692

<?php
$json = '[{"date": "2011-08-07", "name": "bob"},{"date": "2011-07-07", "name": "jones"},{"date": "2011-09-03", "name": "blair"},{"date": "2009-01-01", "name": "test"}]';
$arr = json_decode($json, true);
print_r($arr);
function cmp($a, $b)
{
    return strcmp($a['date'], $b['date']);
}
usort($arr, "cmp");
print_r($arr);
?>

Open in new window

0
 
LVL 4

Author Closing Comment

by:Brant Snow
ID: 34094896
great
0

Featured Post

Does Powershell have you tied up in knots?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question