PHP JSON从关联数组STUCK中排序

时间:2015-12-04 17:09:06

标签: php arrays json

对那些比我更聪明的人来说,这是美好的一天。我一直都在谷歌,这里无济于事。这是我的情况......我有一个json文件:

    {
"firstset": {
    "xgroup": [
    {
        "order": 3,
        "title": "third in xgroup"
    }, {
        "order": 5,
        "title": "fifth in xgroup"
    }, {
        "order": 4,
        "title": "fourth in xgroup"
    }, {
        "order": 1,
        "title": "first in xgroup"
    }, {
        "order": 2,
        "title": "second in xgroup"
    }
    ]
},
"secondset": {
    "ygroup": [
    {
        "order": 7,
        "title": "seventh in ygroup"
    }, {
        "order": 4,
        "title": "fourth in ygroup"
    }, {
        "order": 6,
        "title": "sixth in ygroup"
    }, {
        "order": 1,
        "title": "first in ygroup"
    }, {
        "order": 3,
        "title": "third in ygroup"
    }, {
        "order": 2,
        "title": "second in ygroup"
    }, {
        "order": 8,
        "title": "eighth in ygroup"
    }, {
        "order": 5,
        "title": "fifth in ygroup"  
    }
    ]
}

}

这是PHP:

    $json_url = "js/testlist.json";
    $json = file_get_contents($json_url);
    $data = json_decode($json, TRUE);

    echo '<ul>';
    foreach ($data['firstset']['xgroup'] as $val) {
        echo '<li>' . $val['order'] . '.) ' . $val['title'] . '</li>';
    }
    echo '</ul>';

我已经尝试过老式的my_sort&#39;在这里找到的函数只是用尽整个数组而无济于事。有没有办法按顺序排序&#39;第一集&#39;上的字段数组并显示数据?

提前谢谢你......

1 个答案:

答案 0 :(得分:0)

要扩展我的评论,请点击以下页面

$data = json_decode($json, true);
//array_column: use values of order key as keys, title key as value
$data['firstset']['xgroup'] = array_column(
    $data['firstset']['xgroup'],
    'title',//pass null here to assign the entire array to the order key (ie [order => x, title => some title])
    'order'
);
//sort the result by key
ksort($data['firstset']['xgroup']);
foreach ($data['firstset']['xgroup'] as $order => $title) {
    //use vars here
}

Demo here

这需要PHP 5.5或更高版本,所以如果您正在运行PHP 5.4,只需编写一个简单的循环:

$ordered = array();
foreach ($data['firstset']['xgroup'] as $arr) {
    $ordered[$arr['order']] = $arr['title'];
}
ksort($ordered);
foreach ($ordered as $order => $title) {
    //same as before
}

有一个PHP实现(AFAIK)与原生array_column函数完全兼容on github