1

I've got the following JSON:

{
"row":  [
    {
    "sort":3,
    "type":"fat",
    "widgets":
        [
            {"values": [3,9] },
            {"values": [8,4] }                  
        ]
    },
{
    "sort":2,
    "type":"three",
    "widgets":
    [
        {"values": [3,4] },
        {"values": [12,7] },
        {"values": [12,7] }                         
    ]
}                       
]
}

And this PHP to output it:

foreach ( $value->row as $therow )
{
    echo "<div class='row ".$therow->type."'>";

    foreach ( $therow->widgets as $thewidgets )
    {
        echo "<div class='widget'>";
        echo $thewidgets->values[0];
        echo "</div>";

    }

    echo "</div>";

}

What I would like to do is sort the ouput based on the sort value in the JSON, any ideas?

Tom
  • 30,868
  • 31
  • 81
  • 104

4 Answers4

4

Use usort:

function my_sort($a, $b)
{
    if ($a->sort < $b->sort) {
        return -1;
    } else if ($a->sort > $b->sort) {
        return 1;
    } else {
        return 0;
    }
}

usort($value->row, 'my_sort');
Tobias Cohen
  • 19,480
  • 7
  • 51
  • 51
2

See here:

Sorting an associative array in PHP

for user-defined sorting.

Community
  • 1
  • 1
Stefan Gehrig
  • 78,962
  • 24
  • 149
  • 181
0

See following if you want to do it on client side.

Sorting JSON by values

Community
  • 1
  • 1
Tahir Akhtar
  • 10,902
  • 7
  • 40
  • 67
0

Just sort the data before printing it in the second foreach loop:

foreach ($value->row as $therow) {
    if ($therow->sort == 2) {
        // sort $therow->widgets according to whatever sort 2 means
    } elseif ($therow->sort == 3) {
        // sort $therow->widgets according to whatever sort 3 means
    }
    echo "<div class='row ".$therow->type."'>";
    foreach ($therow->widgets as $thewidgets) {
        echo "<div class='widget'>";
        echo $thewidgets->values[0];
        echo "</div>";
    }
    echo "</div>";
}
Gumbo
  • 594,236
  • 102
  • 740
  • 814