douzhi1813 2017-10-10 21:04
浏览 50
已采纳

PHP排序多维数组失败

I have this array :

Array
(
    [0] => Array
        (
            [id] => 83
            [value] => Figures
        )

    [1] => Array
        (
            [id] => 85
            [value] => Toys
        )

    [2] => Array
        (
            [id] => 36
            [value] => Nintendo Switch
        )

)

and I have this code to sort that array based on id :

function cmp($a, $b) {
    return strcmp($a->id, $b->id);
}

while ($row = $result->fetch_assoc()) {

    $category = json_decode($row['product_cat'], true);

    usort($category, "cmp");

    echo '<pre>';
    print_r($category);
    echo '</pre>';
}

the result is not working as I expected, because id=85 placed before id=83 :

Array
(
    [0] => Array
        (
            [id] => 36
            [value] => Nintendo Switch
        )

    [1] => Array
        (
            [id] => 85
            [value] => Toys
        )

    [2] => Array
        (
            [id] => 83
            [value] => Figures
        )

)

why PHP successfully placed the id=36 as first value of array, but failed to sort id=85 and id=83

thank you.

展开全部

  • 写回答

4条回答 默认 最新

  • dongqing483174 2017-10-10 21:13
    关注

    change

    return strcmp($a->id, $b->id);
    

    to

    return strcmp($a['id'], $b['id']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部