0

I have to sort names according to serial nos. Following is the code which I want to sort by the serial no.

$data = json_decode($result,true);

$v1 = $data['Data'];
foreach($v1 as $key => $value)
{
$name = $value['Name'];
$order = $value['SerialNo'];

   echo $name . '<br>';
   echo $order . '<br>';
}

I have tried sort($v1); which sort the whole data but not serial wise. I have tried the following;

function srt($a, $b)
{
    if ($a < $b) {
        return -1;
    } else if ($a > $b) {
        return 1;
    } else {
        return 0; 
    }
}
usort($v1, 'srt');

JSON data

{"Math":{"Name":"John","SerialNo":"4"},"Science":{"Name":"Peter","SerialNo":"1"},"English":{"Name":"Kyle","SerialNo":"3"},"German":{"Name":"Neena","SerialNo":"2"},"Art":{"Name":"Rita","SerialNo":"5"}}

This doesn't sort the data as per serial no. If I put in $order instead of $v1 in function I get error that function requires array and string is given instead.

How to sort the names according to serial no. then?

thanks, AK

AK Singh
  • 9
  • 2
  • 2
    You need to compare `$a['SerialNo']` and `$b['SerialNo']`. If they are numeric values, just `return $a['SerialNo'] - $b['SerialNo'];`. If they are strings, you can use `return strcmp($a['SerialNo'],$b['SerialNo']);`. – Niet the Dark Absol May 08 '18 at 07:40
  • Can you include the json so that we can give you an answer? – Andreas May 08 '18 at 07:41
  • the duplicate answer is very detailed and contains loads of different sorting algorithms. I think you need `usort()` however, so look here https://delboy1978uk.wordpress.com/2012/09/19/sorting-multidimensional-arrays-using-php/ – delboy1978uk May 08 '18 at 07:47
  • @Andreas Have updated the json code. I want to arrange data (Math / Name etc.) according to serial no. ? – AK Singh May 08 '18 at 08:38
  • @NiettheDarkAbsol I tried both the approaches but just can't seem to sort this. Can you elaborate? I've also updated JSON data. – AK Singh May 08 '18 at 09:30

0 Answers0