0

I have two arrays with around 50 fields each, one is an array of users, which was obtained from db and looks like this (shortened to only 3 fields)

Array( [0] => Array([id] => 1 [email] => [email protected] [last_name] => Lastname)
       [1] => Array([id] => 2 [email] => [email protected] [last_name] => Lastname2)
     );

My other array, is an array of fields, where key is the name of the field, and value is the field in the users table (shortened as well):

Array([User ID] => id [Last Name] => last_name [Email] => email);

Now, I want to produce an array to compare two users, and after a couple of foreach I got this array:

 Array([id] => Array([0] => 1 [1] => 2)
          [email] => Array([0] => [email protected] [1] => [email protected])
          [last_name] => Array([0] => Lastname [1] => Lastname2)

This last array, as you can see, contains the id for the two users, email for both, etc. which is used to make comparisons. This works, however, you can see that the order does not correspond to the names of the fields array. I would like the third array to be created according to the order of the second array (that is, 1) id, 2) last name, 3) email)

How can that be achieved?

  • Why do you need to sort it as mentioned. As it's an associative array, you can just loop through your second array (i.e. your desired order) and access corresponding element from third. Is there any particular need to sort? – Vikk Oct 25 '11 at 16:22
  • Of course there is a particular need to sort, otherwise I wouldn't be asking. – luqita Oct 25 '11 at 16:30
0
<?php
$newArray = array();
$rows = Array(
   Array('id' => 1, 'email' => '[email protected]', 'last_name' => 'Lastname'),
   Array('id' => 2, 'email' => '[email protected]', 'last_name' => 'Lastname2')
 );
$fields = Array('User ID' => 'id', 'Last Name' => 'last_name', 'Email' => 'email');
foreach (array_values($fields) as $field) {
    $newArray[$field] = array();
    foreach ($rows as $singleRow) {
        $newArray[$field][] = $singleRow[$field];
    }
}
var_dump($newArray);

As you can see, I used another array for ordering.

0
array_merge(array_fill_keys(array('id', 'lastname', 'email'), null)
   , $comparison_arrays
);

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.