我如何对循环创建的数组进行排序?

how can i sort array which is create of a loop?

function sortpm($parameters){
if(strpos($parameters,"&")!==false){
    foreach(explode("&",$parameters) as $pmsplit){
        $key = explode("=",$pmsplit)[0];
        $value = explode("=",$pmsplit)[1];
        $fields[]=[$key=>$value];
    }
   $parameters = ksort($fields);
}else{
        $parameters = $parameters;
}
print_r($parameters);
}

当我得到 sortpm("z=4&a=2"); 数组未按键排序

我想要这个输出:Array ( [a] => 2[z] => 4 )

ksort 将对 $fields 数组进行排序,并将 return 设为布尔值。你会想要这样的东西:

$parameters = $fields;
ksort($parameters);

这里也发生了一些不必要的事情。我会像这样重写你的代码:

function sortpm($parameters){
    // Make sure to set a default value to your variables
    $fields = [];
    // No need for the if case - explode will always return an array
    foreach(explode("&",$parameters) as $pmsplit){
        // Instead of exploding twice - explode once, but set a limit
        $exploded = explode("=", $pmsplit, 2);
        // If there is no second parameter, fill in a null value
        $fields[$exploded[0]]= isset($exploded[1]) ? $exploded[1] : null;
    }
   ksort($fields);
   print_r($fields);
}

或者您可以将 parse_str 用作