duanjiagu0655 2012-03-18 17:12
浏览 26
已采纳

按键值排序数组

So I have this array.

Array
(
    [0] => Array
        (
            [key_1] => something
            [type] => first_type
        )

    [1] => Array
        (
           [key_1] => something_else
           [type] => first_type
        )

    [2] => Array
        (
            [key_1] => something_else_3
            [type] => second_type
        )

    [3] => Array
        (
            [key_1] => something_else_4
            [type] => second_type
        )
)

I have to sort by type value in a pattern like this:

first_type
second_type
first_type
second_type

My questions is, how can I do this?

Thanks a lot!

  • 写回答

3条回答 默认 最新

  • dongshanjin8947 2012-03-20 13:50
    关注

    So here's how I got it to work:

    function filter_by_value($array, $index, $value) { 
        if(is_array($array) && count($array) > 0)  { 
            foreach(array_keys($array) as $key){ 
                $temp[$key] = $array[$key][$index]; 
                if ($temp[$key] == $value){ 
                    $newarray[$key] = $array[$key]; 
                } 
            } 
        } 
        return $newarray;
    }
    $array = /* array here */ 
    $type1 = array_values(filter_by_value($array, 'type', '1'));
    $type2 = array_values(filter_by_value($array, 'type', '2'));
    $i = 1; $x = 1; $y = 1;
    $sorted = array();
    foreach ($array as $a) {
        if ($i % 2) {
            $sorted[$i-1] = $type1[$x-1];
            $x++;
        } else {
            $sorted[$i-1] = $type2[$y-1];
            $y++;
        }
        $i++;
    }
    

    Found filter_by_value() on php.net but I don't remember where so, that's not made by me. Maybe this is not the best solution but it works pretty fine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?