Home >Backend Development >PHP Tutorial >Array sorting - PHP uses system functions to sort one array by the value of another array

Array sorting - PHP uses system functions to sort one array by the value of another array

WBOY
WBOYOriginal
2016-10-10 11:56:201768browse

There are two arrays as follows:

<code>array (size=6)
  0 => string 'id' (length=2)
  1 => string 'name' (length=4)
  2 => string 'identityId' (length=10)
  3 => string 'phone' (length=5)
  4 => string 'email' (length=5)
  5 => string 'schoolId' (length=8)
array (size=6)
  'id' => string '唯一标识' (length=12)
  'identityId' => string '身份证' (length=9)
  'phone' => string '手机号' (length=9)
  'email' => string '邮箱' (length=6)
  'name' => string '姓名' (length=6)
  'schoolId' => string '学校' (length=6)</code>

How to sort the second array by the key value of the first array, that is, the second array becomes id, name, identityId...
Use system functions, thank you everyone

Reply content:

There are two arrays as follows:

<code>array (size=6)
  0 => string 'id' (length=2)
  1 => string 'name' (length=4)
  2 => string 'identityId' (length=10)
  3 => string 'phone' (length=5)
  4 => string 'email' (length=5)
  5 => string 'schoolId' (length=8)
array (size=6)
  'id' => string '唯一标识' (length=12)
  'identityId' => string '身份证' (length=9)
  'phone' => string '手机号' (length=9)
  'email' => string '邮箱' (length=6)
  'name' => string '姓名' (length=6)
  'schoolId' => string '学校' (length=6)</code>

How to sort the second array by the key value of the first array, that is, the second array becomes id, name, identityId...
Use system functions, thank you everyone

<code><?php

$a = [
    'id',
    'name',
    'identityId',
    'phone',
    'email',
    'schoolId'
];

$b = [
    'id' => '唯一标识',
    'identityId' => '身份证',
    'phone' => '手机号',
    'email' => '邮箱',
    'name' => '姓名',
    'schoolId' => '学校'
];

var_dump(array_merge(array_flip($a), $b));</code>

Use system function array_muiltsort

<code class="php">$arr1 = array(
    'id',
    'name',
    'identityId',
    'phone',
    'email',
    'schoolId'
);
$arr2 = array(
    'id' => '唯一标识',
    'identityId' => '身份证',
    'phone' => '手机号',
    'email' => '邮箱',
    'name' => '姓名',
    'schoolId' => '学校',
);
array_multisort($arr1,SORT_DESC,$arr2);
print_r($arr2);
// 结果为:
Array
(
    [schoolId] => 学校
    [email] => 邮箱
    [identityId] => 身份证
    [phone] => 手机号
    [id] => 唯一标识
    [name] => 姓名
)
</code>

$a = ['id','name','identityId','phone','email','schoolid'];
$b = ......;
foreach($a as $v) {

<code>$c[$v] = $b[$v];</code>

}
$c is the array you want;

<code>$c = array();
foreach ($a as $value) $c[$value] = $b[$value];
print_r($c);</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn