hungbad
hungbad

Reputation: 75

Change array key in PHP

I have an array which looks like this

Array
(
[1] => Array
    (
        [0] => asdasd
        [company] => asdasd
        [1] => ASDSADASD
        [firstname] => ASDSADASD
        [2] => ASDSAD
        [lastname] => ASDSAD
        [3] => [email protected]
        [email] => [email protected]
        [4] => 58
        [user_id] => 58
    )

[2] => Array
    (
        [0] => asdasd
        [company] => asdasd
        [1] => Hưng
        [firstname] => Hưng
        [2] => asdasdasd
        [lastname] => asdasdasd
        [3] => [email protected]
        [email] => [email protected]
        [4] => 59
        [user_id] => 59
    )

)

1 and 2 have the same [company] and I want to change the array key to [company] which should be converted like this. They will be grouped by unique company key.

Array
(
   [asdasd] => Array 
       (
         [1] => Array (
               (
                 [0] => ASDSADASD
                 [firstname] => ASDSADASD
                 [1] => ASDSAD
                 [lastname] => ASDSAD
                 [2] => [email protected]
                 [email] => [email protected]
                 [3] => 58
                 [user_id] => 58
               )

         [2] => Array
               (
                 [0] => Hưng
                 [firstname] => Hưng
                 [1] => asdasdasd
                 [lastname] => asdasdasd
                 [2] => [email protected]
                 [email] => [email protected]
                 [3] => 59
                 [user_id] => 59
               )
       )
)

Please tell my how to do this. Thank you so much.

Upvotes: 0

Views: 78

Answers (2)

ɹɐqʞɐ zoɹǝɟ
ɹɐqʞɐ zoɹǝɟ

Reputation: 4370

ugly solution but works

$comp=$r[1]['company'];

unset($r[1][0]);//if you use fetch_assoc instead of fetch_array then you wont get rid of these numerical keys in array
unset($r[1]['company']);
unset($r[2][0]);
unset($r[2]['company']);

$n[$comp]=$r;
print_r($n);

output as you wanted

Upvotes: 1

Satish Sharma
Satish Sharma

Reputation: 9625

try this

$arr_output = array();
foreach($arr_input as $arr)
{
    $key = $arr['company'];

    for($i=1; $i<sizeof($arr)/2; $i++)
    {
       $arr[$i-1] = $arr[$i]; 
    }
    unset($arr[$i-1]);
    unset($arr['company']);

    $arr_output[$key][] = $arr;

}

print_r($arr_output);

see Demo

Upvotes: 2

Related Questions