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 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM