PHP associative array replace location of the key

Sam asked
php arrays
via

The following array is generated from the database and the key field “comp” is pushed into the array . I want to generate the following output by traversing into the array and replacing the order .

Output of the array

Array
    (
        [0] => Array
            (
                [fname] => Calvin
                [lname] => harris
                [age] => 22
                [comp] => IT
            )

        [1] => Array
            (
                [fname] => zayn
                [lname] => dusk
                [age] => 21
                [comp] => HR
            )

    )

the “comp” key should be listed after “lname” So , if there is a array inbuilt function or an efficient code to obtain the output as shown below.

The expected result should be

Array
(
    [0] => Array
        (
            [fname] => Calvin
            [lname] => harris
            [comp] => IT
            [age] => 22

        )   

)


Answer
via

You can use an array_key_up() function for this.

foreach($arrays as &$array) {
    $array = array_key_up($array, 'comp');
}

Array
    (
        [0] => Array
            (
                [fname] => Calvin
                [lname] => harris
                [comp] => IT
                [age] => 22
            )

        [1] => Array
            (
                [fname] => zayn
                [lname] => dusk
                [comp] => HR
                [age] => 21
            )

    )

The needed function.

function array_key_up($array, $key)
{
    $keys  = array_keys($array);
    $index = array_search($key, $keys, true);

    if ($index === false) {
        return $array;
    }
    $offset = max(0, $index - 1);

    return array_slice($array, 0, $offset, true)
        + array($key => $array[$key])
        + array_slice($array, $offset, null, true);
}
Share This
Posted in: