Scott Paterson Scott Paterson - 6 days ago 5
PHP Question

Reorder array by given key name

I have a PHP array like this:

Array
(
[stripe] => Array
(
[title] => Stripe
)

[paypal_standard] => Array
(
[title] => PayPal Standard
)
)


Given the key 'paypal_standard', how can I reorder the array so that this is the result:

Array
(
[paypal_standard] => Array
(
[title] => PayPal Standard
)
[stripe] => Array
(
[title] => Stripe
)
)


Perhaps I am missing it, but is there a PHP function for doing this?

Edit: I can't sort by alphabetical order.

Answer

Try this:

$response = array(
    'stripe' => array('title' => 'Stripe'),
    'paypal_standard' => array('title' => 'Paypal standard'),
);

$paypal = $response['paypal_standard']; // Filter out the value corresponding to paypal_standard

unset($response['paypal_standard']); // Since filtered out, remove paypal_standard key from array

$response = array('paypal_standard' => $paypal) + $response; // Format the array by adding key value pair for paypal_standard in the beginning

Output:

Array
(
 [paypal_standard] => Array
    (
        [title] => Paypal standard
    )

 [stripe] => Array
    (
        [title] => Stripe
    )

)
Comments