Solved

Sort Json array in php

Posted on 2010-11-08
3
1,106 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
Comment Utility
0
 
LVL 8

Accepted Solution

by:
shanikawm earned 500 total points
Comment Utility

<?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
Comment Utility
great
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

743 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now