php - sort an array by key to match another array's order by key

后端 未结 5 1653
别跟我提以往
别跟我提以往 2020-12-16 01:20

I have two arrays, both have the same keys (different values) however array #2 is in a different order. I want to be able to resort the second array so it is in the same ord

5条回答
  •  没有蜡笔的小新
    2020-12-16 01:48

    You can use array_replace

    $arr1 = [
        'x' => '42', 
        'y' => '551',
        'a' => '512',
        'b' => 'gge',
    ];
    
    
    $arr2 = [
        'a' => 'ordered',
        'x' => 'this',
        'y' => 'is',
        'b' => 'now',
    ];
    
    $arr2 = array_replace($arr1, $arr2);
    

    $arr2 is now

    [
        'x' => this,
        'y' => is,
        'a' => ordered,
        'b' => now,
    
    ]
    

提交回复
热议问题