我们的一维数组数据:
$a = [
100,
102,
104
];
需要按照$a排序的二维数组:
$b = [
104 => [
'id' => '104',
'name' => '104name'
],
105 => [
'id' => '105',
'name' => '105name'
],
102 => [
'id' => '102',
'name' => '102name'
],
100 => [
'id' => '100',
'name' => '100name'
],
101 => [
'id' => '101',
'name' => '101name'
]
];
实现方式:
// 使用键名比较计算数组的交集
$intersect_key = array_intersect_key(array_flip($a), $b);
// 使用后面数组的值替换第一个数组的值
$data = array_replace($intersect_key, $b);
最终返回结果:
array:5 [
100 => array:2 [
"id" => "100"
"name" => "100name"
]
102 => array:2 [
"id" => "102"
"name" => "102name"
]
104 => array:2 [
"id" => "104"
"name" => "104name"
]
105 => array:2 [
"id" => "105"
"name" => "105name"
]
101 => array:2 [
"id" => "101"
"name" => "101name"
]
]