ihtus ihtus - 1 month ago 18
PHP Question

Associative array - change position

For ex have this array:

[food] => Array (
[fruits] => apple
[vegetables] => garlic
[nuts] => cashew
[meat] => beaf
)


I need to change the position of a specific key-value combination.

Let's say I need to move [fruits] => apple to 3rd position

[food] => Array (
[vegetables] => garlic
[nuts] => cashew
[fruits] => apple
[meat] => beaf
)


I am not talking about sorting by key or value.
I need to change position of key-value to a very strict new position.

Something like:

change_pos($my_arr, $key_to_move, $new_index);


=>

change_pos($my_arr, "fruits", 3);


Is that possible?

Answer

It was hard , but finally:

<?php
function array_splice_assoc(&$input, $offset, $length, $replacement) {
        $replacement = (array) $replacement;
        $key_indices = array_flip(array_keys($input));
        if (isset($input[$offset]) && is_string($offset)) {
                $offset = $key_indices[$offset];
        }
        if (isset($input[$length]) && is_string($length)) {
                $length = $key_indices[$length] - $offset;
        }

        $input = array_slice($input, 0, $offset, TRUE)
                + $replacement
                + array_slice($input, $offset + $length, NULL, TRUE);
}
function array_move($which, $where, $array)
{
    $tmpWhich = $which;
    $j=0;
    $keys = array_keys($array);

    for($i=0;$i<count($array);$i++)
    {
        if($keys[$i]==$tmpWhich)
            $tmpWhich = $j;
        else
            $j++;
    }
    $tmp  = array_splice($array, $tmpWhich, 1);
    array_splice_assoc($array, $where, 0, $tmp);
    return $array;
}
$array = array('fruits' => 'apple','vegetables' => 'garlic','nuts' => 'cashew','meat' => 'beaf');
$res = array_move('vegetables',2,$array);
var_dump($res);
?>
Comments