dongroufan6846 2011-12-02 21:41
浏览 93
已采纳

按另一个数组的值对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…

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>

Order

Array
(
    [0] => 2
    [1] => 1
    [2] => 3
)

Data

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

This are the json strings:

order.text

{"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}
  • 写回答

2条回答 默认 最新

  • doutang7707 2011-12-02 21:54
    关注

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

    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);
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?