dongzuo9096 2011-10-25 16:03
浏览 34

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

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] => 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):

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] => 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. 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?

  • 写回答

2条回答 默认 最新

  • dongxiangxie8181 2011-10-25 16:25
    关注
    <?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.

    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个复杂问题的解释说明
  • ¥50 三种调度算法报错 采用的你的方案
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败