2009-05-20 77 views
1

我有以下的JSON:排序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] }       
    ] 
}      
] 
} 

这PHP输出它:

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

} 

我想这样做是有点基础上的输出中在JSON中排序值,有什么想法?

+0

什么样的排序将是“2”或“3”? – Gumbo 2009-05-20 12:46:00

回答

4

使用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

只是在第二foreach循环打印之前对数据进行排序:

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