Home >Backend Development >PHP Tutorial >natsort()排列json数据时报错。解决方法

natsort()排列json数据时报错。解决方法

WBOY
WBOYOriginal
2016-06-13 10:24:041217browse

natsort()排列json数据时报错。

PHP code
<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->$json = '[{"name":"a1"},{"name":"a10"},{"name":"a12"},{"name":"a3"},{"name":"a5"},{"name":"b21"},{"name":"b2"},{"name":"b11"}]';natsort($json);$data = json_decode($json);foreach ($data as $row) {    echo $row->name.'<br>';//}


为什么会提示 Warning: natsort() expects parameter 1 to be array, string given in d:\www\test.php?
另外natsort()和strnatcmp()的区别在哪里?
谢谢。


------解决方案--------------------
natsort 是数组排序函数,不能作用于字符窜

------解决方案--------------------
PHP code
$json = '[{"name":"a1"},{"name":"a10"},{"name":"a12"},{"name":"a3"},{"name":"a5"},{"name":"b21"},{"name":"b2"},{"name":"b11"}]';$data = json_decode($json);usort($data, 'cmp');function cmp($a, $b) {    if ($a->name == $b->name) return 0;    return $a->name > $b->name ? 1 : -1;}foreach ($data as $row) {    echo $row->name.'<br>';//}<div class="clear">
                 
              
              
        
            </div>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn