PHP - 如何按指定值对数组数组进行排序?

时间:2016-02-17 03:19:20

标签: php arrays sorting

我在php中创建了一个数组,我想按名称排序数组的缩进数组,而不是按字母顺序排序。 代码如下:

$arr = array("ID"=>"001",
             "c"=>array()
);

$products = ['apple','orange','kiwi','banana'];

foreach($products as $product){

    $arr['c'][]=array(
        "product" => $product
    );

}

print_r($arr);

上面的代码将打印出来:

    Array(

    [ID] => 001[c] => Array(
          [0] => Array(
            [product] => apple
        ) [1] => Array(
            [product] => orange
        ) [2] => Array(
            [product] => kiwi
        ) [3] => Array(
            [product] => banana
        )
    )
)

我希望在结果中对它们进行排序,如下所示:

Array(

    [ID] => 001[c] => Array(
          [0] => Array(
            [product] => orange 
        ) [1] => Array(
            [product] => apple
        ) [2] => Array(
            [product] => banana
        ) [3] => Array(
            [product] => kiwi
        )
    )
)

1 个答案:

答案 0 :(得分:0)

我试图避免的有趣情况。

如果您已经知道应该订购什么订单,请按正确顺序添加。

$arr = array("ID"=>"001",
             "c"=>array()
);

$products = ['apple','orange','kiwi','banana'];

$myCustomSortValuesInOrder = array (
    'orange', 'apple', 'banana', 'kiwi'
);

foreach($myCustomSortValuesInOrder as $orderVal) {
    $key = array_search($orderVal, $products);
    if($key !== false) {
        $arr['c'][]=array(
            "product" => $products[$key];
        );
    }
}

print_r($arr);