基于数据库列值比较的多维数组排序

时间:2017-09-06 09:13:08

标签: php mysql arrays sorting multidimensional-array

我有以下多维数组

Array
(

    [1] => 22
    [2] => 12
    [3] => Array
        (
            [0] => 4
            [1] => 21
        )

    [5] => Array
        (
            [0] => 9
            [1] => 3
        )

    [7] => 7
    [8] => 6
    [9] => 1
    [10] => 2
    [11] => 10
    [12] => 0
    [13] => 23
    [14] => 18
    [15] => 16
    [16] => 19
    [17] => 15
    [18] => 5
    [19] => 8
    [20] => 11
    [21] => 13
    [22] => 17
    [23] => 14
    [24] => 20
)

我想从主数组中排序数组以下的一个值。

Array
(

    [3] => Array
        (
            [0] => 4
            [1] => 21
        )

    [5] => Array
        (
            [0] => 9
            [1] => 3
        )
)

每个键值与数据库列进行比较并对数组进行排序。如果找不到值,则数组保持不变。 例如:  下面的键值是21,在数据库列中,然后预期结果为,

[3] => Array
    (

        [0] => 21
        [1] => 4

    )

看作下一个数组,数据库中找不到下一个数组键值,然后按预期结果,

[5] => Array
    (

        [0] => 9
        [1] => 3

    )

最终输出查找,

Array
(

    [1] => 22
    [2] => 12
    [3] => Array
        (
            [0] => 21
            [1] => 4
        )

    [5] => Array
        (
            [0] => 9
            [1] => 3
        )

    [7] => 7
    [8] => 6
    [9] => 1
    [10] => 2
    [11] => 10
    [12] => 0
    [13] => 23
    [14] => 18
    [15] => 16
    [16] => 19
    [17] => 15
    [18] => 5
    [19] => 8
    [20] => 11
    [21] => 13
    [22] => 17
    [23] => 14
    [24] => 20
)

你能帮我吗

2 个答案:

答案 0 :(得分:0)

试试这个

foreach($array as $k => $v){

        if(is_array($v)){

         rsort($array[$k]); 

        }

}

print_r($array);

答案 1 :(得分:0)

检查一下。

$dump_array=Array('1' => 2,'2' => 12,'3' => Array
    ('0' => 8,'1' => 21 ),
'5' => Array ('0' => 9,'1' => 3),
'7' => 7,
'8' => 64,
'9' => 15,
'10' => 22,

    );
echo "<pre> Soure :"; print_r($dump_array);echo "</pre>";
sort($dump_array);
$result_array=array();
$array_unlist=array();
foreach($dump_array as $key=>$value){
    if(is_array($value)){
        sort($value);
        array_push($array_unlist,$value);
    }
    else {array_push($result_array,$value);}
}
foreach($result_array as $index=>$val){
    foreach($array_unlist as $key=>$digit){
        if($val<$digit[0])
        {
            $res=$index.".5";
            $result_array[$res]=$digit;
        }
    }
}

ksort($result_array);

echo "<pre> Result :"; print_r(array_values($result_array));echo "</pre>";

输出:

 Soure :Array
(
    [1] => 2
    [2] => 12
    [3] => Array
        (
            [0] => 8
            [1] => 21
        )

    [5] => Array
        (
            [0] => 9
            [1] => 3
        )

    [7] => 7
    [8] => 64
    [9] => 15
    [10] => 22
)
 Result :Array
(
    [0] => 2
    [1] => Array
        (
            [0] => 3
            [1] => 9
        )

    [2] => 7
    [3] => Array
        (
            [0] => 8
            [1] => 21
        )

    [4] => 12
    [5] => 15
    [6] => 22
    [7] => 64
)