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 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用