在PHP中对JSON输出进行排序

时间:2009-05-20 12:39:23

标签: php arrays json sorting

我有以下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中的排序值,任何想法对输出进行排序?

4 个答案:

答案 0 :(得分: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');

答案 1 :(得分:2)

见这里:

Sorting an associative array in PHP

用于用户定义的排序。

答案 2 :(得分:0)

如果您想在客户端执行此操作,请参阅以下内容。

Sorting JSON by values

答案 3 :(得分: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>";
}