0

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.

2
  • Build a new array based on the information of this one Commented May 24, 2014 at 9:22
  • This is mysql_fetch array result. So I want to have a code to change the key automatically :) Commented May 24, 2014 at 9:28

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.