Sorting an array

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
helpplease452
New php-forum User
New php-forum User
Posts: 2
Joined: Sat Mar 25, 2017 5:43 am

Sat Mar 25, 2017 5:46 am

Hi

I was wondering if someone could help. I've got a Json array called $data which looks like this:

{
"england":{
"goals":"2",
"games":"3",
"wins":"2",
"loss":"1"
},
"wales":{
"goals":"2",
"games":"3",
"wins":"2",
"loss":"1"
},
"scotland":{
"goals":"2",
"games":"3",
"wins":"2",
"loss":"1"
}
}


What would be the easiest way to sort alphabetically by the team name?

Thanks in advance
AdoptiveSolution
php-forum Super User
php-forum Super User
Posts: 167
Joined: Wed Jun 15, 2016 8:35 am

Sat Mar 25, 2017 7:32 am

Try this :

Code: Select all

<?php

$json = '{
	"england":{
		"goals":"2",
		"games":"3",
		"wins":"2",
		"loss":"1"
	},
	"wales":{
		"goals":"2",
		"games":"3",
		"wins":"2",
		"loss":"1"
	},
	"scotland":{
		"goals":"2",
		"games":"3",
		"wins":"2",
		"loss":"1"
		}
}';

$array = json_decode($json, true);

echo '<pre>';
var_dump($array);
echo '</pre>';

ksort($array);

echo '<pre>';
var_dump($array);
echo '</pre>';

?>
http://php.net/manual/en/array.sorting.php
helpplease452
New php-forum User
New php-forum User
Posts: 2
Joined: Sat Mar 25, 2017 5:43 am

Sat Mar 25, 2017 7:42 am

Thanks for your help. I'm new to coding but that was extremely easy, feel a bit of an idiot now :o)
Post Reply