我有两个PHP数组。第一个包含排序顺序。第二个包含我需要排序的数据。我不知道如何解决它......
我想要得到的是一个列表,按第一个数组(order.txt)的值排序。有什么建议吗?
<li>Item [2]</li>
<li>Item [1]</li>
<li>Item [3]</li>
Array
(
[0] => 2
[1] => 1
[2] => 3
)
Array
(
[0] => Array
(
[id] => 1
[name] => 00134258.jpg
[size] => 2787
)
[1] => Array
(
[id] => 2
[name] => 80132454.jpg
[size] => 2667
)
[2] => Array
(
[id] => 3
[name] => 13134218.jpg
[size] => 2787
)
)
以下是生成上述数组的代码:
<?php
$order = file('order.txt');
foreach ($order as $key => $value) {
$order = json_decode($value, true);
}
print_r($order);
$file = file('db.txt');
foreach ($file as $key => $value) {
$file_data[] = json_decode($value, true);
}
print_r($file_data);
?>
这是json字符串:
{"0":"2","1":"1","2":"3"}
{"id":"1","name":"00134258.jpg","size":2787}
{"id":"2","name":"80132454.jpg","size":2667}
{"id":"3","name":"13134218.jpg","size":2787}
答案 0 :(得分:2)
从$order
数组中减去每个值的1,然后使用array_multisort
:
foreach($order as &$o) $o--;
unset($o);
array_multisort($order, $data);
只要id
值始终高于$data
中的偏移量,就可以使用此功能。
答案 1 :(得分:2)
创建一个新数组,其中键是数据的id,然后遍历您的order数组并将值分配给有序数组...
<?php
// loop through the file data
foreach($file_data as $v){
// assign values to new array with the data id as it's key
$identified[$v['id']] = $v;
}
// loop through the order array
foreach($order as $v){
// pull the data values from the identified array by their key
$ordered[] = $identified[$v];
}
// check it has all worked out as planned ;)
print_r($ordered);
?>
或者......与@hakre的方法一致,首先创建按索引排序的数组,然后使用array_multisort方法。
<?php
foreach($file_data as $v){
$ordered[$v['id']] = $v;
}
array_multisort($order, $ordered);
print_r($ordered);
?>