Solved

Sort Json array in php

Posted on 2010-11-08
3
1,252 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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

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…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

856 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