douyan6871 2016-03-16 22:17
浏览 39
已采纳

按多维数组值对多维数组进行排序

I want to use the 'id' array of Array 1 to order all other sibling arrays in Array 2. The 'id' array is supposed to act as the schema for all other arrays in $array1 and $array2.

This is easier explained with an example.

I have the following array, Array 1 :

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

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

And another array, Array 2:

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

    [headline] => Array
        (
            [0] => tc test 1
            [1] => tc test 2
            [2] => tc test 3
        )
)

That I would like to look like the following:

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

    [headline] => Array
        (
            [0] => tc test 1
            [1] => tc test 3
            [2] => tc test 2
        )

)

Right now I'm trying to force it with foreach statements (and failing), but there has to be a better way.

  • 写回答

1条回答 默认 最新

  • douzhang5295 2016-03-17 00:31
    关注

    This is a “fake” sort, because I fill an empty array through a foreach() loop, then I replace original array:

    $array1 = [ 'id' => [ 1,3,2 ], 'headline' => [ 'test 1','test 3','test 2' ] ];
    $array2 = [ 'id' => [ 1,2,3 ], 'headline' => [ 'test 1','test 2','test 3' ] ];
    
    $result = array();
    foreach( $array1['id'] as $val )
    {
        $key = array_search( $val, $array2['id'] );
        $result['id'][]       = $array2['id'][$key];
        $result['headline'][] = $array2['headline'][$key];
    }
    $array2 = $result;
    
    print_r( $array2 );
    

    Output:

    Array
    (
        [id] => Array
            (
                [0] => 1
                [1] => 3
                [2] => 2
            )
        [headline] => Array
            (
                [0] => test 1
                [1] => test 3
                [2] => test 2
            )
    )
    

    I execute a foreach loop through criterion 'id' array, find each value in array to be sorted, retrieve its key and use it to add values to resulting array.

    Not so proud of this solution, but this is.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于螺旋焊缝的图像处理
  • ¥15 qt 散点图自定义图形
  • ¥100 将USDZ文件转化为带颜色的OBJ文件
  • ¥15 对象代号: , 表单: 不存在!
  • ¥15 WebSocket的问题
  • ¥15 centos上启动kylin后网页报错404
  • ¥20 使用hackrf进行信号收发时接收到的信号幅度太小
  • ¥15 WebSocket的问题
  • ¥15 BDSBAS-B1C和B1C信号有什么不同
  • ¥15 在半圆平面内随机生成点坐标
  • ¥100 理想汽车的USB调试为什么到了国外换了SIM就可以打开?