简体   繁体   English

PHP:根据另一个数组进行数组排序

[英]PHP: Array sorting according to another array

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) 我有两个数组,每个数组有大约50个字段,一个是用户数组,它是从db获得的,看起来像这样(缩短为3个字段)

Array( [0] => Array([id] => 1 [email] => email1@hotmail.com [last_name] => Lastname)
       [1] => Array([id] => 2 [email] => email2@hotmail.com [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): 我的另一个数组是字段数组,其中key是字段的名称,value是users表中的字段(也简称为):

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: 现在,我想产生一个比较两个用户的数组,经过两次foreach之后,我得到了这个数组:

 Array([id] => Array([0] => 1 [1] => 2)
          [email] => Array([0] => email1@hotmail.com [1] => email2@hotmail.com)
          [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. 如您所见,最后一个数组包含两个用户的ID,两个用户的电子邮件等,用于进行比较。 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) 我希望根据第二个数组的顺序创建第三个数组(即1)id,2)姓氏,3)电子邮件)

How can that be achieved? 如何实现?

<?php
$newArray = array();
$rows = Array(
   Array('id' => 1, 'email' => 'email1@hotmail.com', 'last_name' => 'Lastname'),
   Array('id' => 2, 'email' => 'email2@hotmail.com', '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. 如您所见,我使用了另一个数组进行排序。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM