如何在 PHP 中重新排序数组元素

下面是排序数组的函数。
它适用于关联数组和索引数组,包括字符串、整数和布尔值——并且它也保留了键。

function array_shove(array $array, $selected_key, $direction)
{
    $new_array = array();
    foreach ($array as $key => $value) {
        if ($key !== $selected_key) {
            $new_array["$key"] = $value;
            $last = array('key' => $key, 'value' => $value);
            unset($array["$key"]);
        } else {
            if ($direction !== 'up') {
                //Value of next, moves pointer
                $next_value = next($array);
                //Key of next
                $next_key = key($array);
                //Check if $next_key is null,
                //indicating there is no more elements in the array
                if ($next_key !== null) {
                    //Add -next- to $new_array, keeping -current- in $array
                    $new_array["$next_key"] = $next_value;
                    unset($array["$next_key"]);
                }
            } else {
                if (isset($last['key'])) {
                    unset($new_array["{$last['key']}"]);
                }
                //Add current $array element to $new_array
                $new_array["$key"] = $value;
                //Re-add $last to $new_array
                $new_array["{$last['key']}"] = $last['value'];
            }
            //Merge new and old array
            return $new_array + $array;
        }
    }
}

要使用该函数,只需这样做:

$contact_array = array(
    'admin' => 'admin@example.com',
    'webmaster' => 'webmaster@example.com',
    'support' => 'support@example.com',
    'reception' => 'reception@example.com',
);
//last parameter can either be "up" or "down"
$reordered = array_shove($contact_array, 'webmaster', 'down');
//Show the re-ordered array
print_r($reordered);

如果要将数组存储为 JSON:

echo json_encode($reordered);

建议在并发情况下使用文件处理程序类。

日期:2020-06-02 22:17:14 来源:oir作者:oir