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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵