Solved

Sort Json array in php

Posted on 2010-11-08
3
1,291 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

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

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
This article discusses how to implement server side field validation and display customized error messages to the client.
The viewer will learn how to count occurrences of each item in an array.
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…

726 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