2009-05-20 3 views
1

ich folgende JSON haben:Sortierung JSON Ausgabe in PHP

{ 
"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] }       
    ] 
}      
] 
} 

Und diese PHP ausgeben es:

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>"; 

} 

Was Ich mag würde, ist zu tun Art der ouput auf der Basis Sort Wert im JSON, irgendwelche Ideen?

+0

Und welche Art von Art würde „2“ oder „3“ sein? – Gumbo

+1

Die Reihenfolge der Zeile, wie sie im Backend erstellt wurde – Tom

Antwort

4

Verwendung 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'); 
0

einfach die Daten sortieren, bevor er in der zweiten foreach Schleife Druck:

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>"; 
}