是否有一种简单的方法可以使用为此任务创建的变量数组对数组进行排序? 例如:
$fruits [
'Apple' => '12',
'Cherry' => '10',
'Lemon' => '34',
'Peach' => '6'
]
$order [
1 => 'Peach',
2 => 'Other',
3 => 'Lemon',
4 => 'Other2',
5 => 'Apple',
6 => 'Cherry',
7 => 'Other3'
]
我想返回这种数组:
$ordered_fruits [
'Peach' => '6',
'Lemon' => '34',
'Apple' => '12',
'Cherry' => '10'
]
答案 0 :(得分:4)
$ordered_fruits = array();
foreach($order as $value) {
if(array_key_exists($value,$fruits)) {
$ordered_fruits[$value] = $fruits[$value];
}
}
答案 1 :(得分:3)
用php函数制作:
$new = array_filter(array_replace(array_fill_keys($order, null), $fruits));
答案 2 :(得分:2)
试试这个:
$fruits = array(
'Apple' => '12',
'Cherry' => '10',
'Lemon' => '34',
'Peach' => '6'
);
$order = array(
1 => 'Peach',
2 => 'Other',
3 => 'Lemon',
4 => 'Other2',
5 => 'Apple',
6 => 'Cherry',
7 => 'Other3'
);
$result = array();
foreach ($order as $key => $value) {
if ( array_key_exists($value, $fruits) ) {
$result[$value] = $fruits[$value];
}
}
print_r($result );
答案 3 :(得分:1)
排序技巧:
$result = array();
foreach($order as $value){
if(array_key_exists($value, $fruits)){
$result[$value] = $fruits[$value];
}
}
<强>结果强>
print_r($result);
Array
(
[Peach] => 6
[Lemon] => 34
[Apple] => 12
[Cherry] => 10
)