[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 224
  • Last Modified:

Sorting by Alpha J SON array from API

I am trying to sort a JSON array by "resortName". I have the JSON output here: http://pastie.org/2539795

I am parsing my JSON with PHP using:

<?php 
$type = $_GET["type"];
$jsonurl = "http://feeds.snocountry.com/conditions.php?apiKey=skimaine$54.maineski118&states=ME&resortType=".$type."";
$json_string = file_get_contents($jsonurl,0,null,null);
echo sort(json_string);
?>

Open in new window


I am trying to sort by this item in the array : "resortName": "Black Mountain" by alpha.

Any ideas?

Thanks.
0
catonthecouchproductions
Asked:
catonthecouchproductions
  • 2
1 Solution
 
R-ByterCommented:
Here you go:

<?php
	error_reporting(E_ALL);
	
	function cmp($a, $b)
	{
		if (strtolower($a->resortName) == strtolower($b->resortName)) {
			return 0;
		}
		return (strtolower($a->resortName) < strtolower($b->resortName)) ? -1 : 1;
	}

	$json_string = file_get_contents("json.txt");
	$json_string = json_decode($json_string);
	usort($json_string->items, 'cmp');	
	$json_string = json_encode($json_string);
	
	echo $json_string;
?>

Open in new window


You should use PHP usort and your own defined comparison function.
When you get the string with file_get_contents, decode it (convert to object). Use usort to sort it by defined item and re-encode it to json.

Regards
0
 
R-ByterCommented:
For this example I took JSON from your post and made json.txt of it.

Regards
0
 
Ray PaseurCommented:
Usort() is the right answer.  It sorts arrays, not strings, and that is why json_decode() is needed to recreate the array.
http://php.net/manual/en/function.usort.php

But please do us a favor going forward.  Please use the EE functionality for file uploads and code snippets.  It's much easier to get access to the tools we need to answer your questions if we don't have to deal with external sites like "pastie."

This page might also be useful...
http://php.net/manual/en/array.sorting.php
0
 
catonthecouchproductionsAuthor Commented:
Worked perfect, thank you! Sorry for the delay on answering.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now