douzhi1813 2017-10-11 05: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-11 05:13
    关注

    change

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

    to

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里