按另一个数组的值对Php数组的数据进行排序 [英] Sort data of Php array by values of another array

查看:50
本文介绍了按另一个数组的值对Php数组的数据进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个PHP数组.第一个包含排序顺序.第二个包含我需要排序的数据.我不知道该怎么解决...

I've two PHP Arrays. The first one contains a sort order. The second one contains the data which i need to sort. I have no idea how to solve it…

我要获取的是一个列表,按第一个数组(order.txt)的值排序.有什么建议吗?

What I'm trying to get is a list, sorted by the values of the first array (order.txt). Any suggestions?

<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
        )

)

以下是产生上述数组的代码:

Here are the code which produces the arrays above:

<?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"}

db.txt

{"id":"1","name":"00134258.jpg","size":2787}
{"id":"2","name":"80132454.jpg","size":2667}
{"id":"3","name":"13134218.jpg","size":2787}

推荐答案

创建一个新数组,其中键是数据的ID,然后遍历您的order数组并将值分配给有序数组...

Make a new array where the keys are the id of the data, then loop through your order array and assign the values to an ordered array...

<?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方法.

Alternatively... in line with @hakre's method, first create array ordered by index, and then use array_multisort method.

<?php
  foreach($file_data as $v){
    $ordered[$v['id']] = $v;
  }
  array_multisort($order, $ordered);
  print_r($ordered);
?>

这篇关于按另一个数组的值对Php数组的数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆