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

后端 未结 5 1644
别跟我提以往
别跟我提以往 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条回答
  •  -上瘾入骨i
    2020-12-16 01:46

    I am not completely sure if this is what your after. anyways as long as the the array remains the same size, than this should work for you.

    $gamey = array ("wow" => "World of Warcraft", "gw2" => "Guild Wars2", "wiz101" => "Wizard 101");
    $gamex = array ("gw2" => "best game", "wiz101" => "WTF?", "wow" => "World greatest");
    
    
    function match_arrayKeys ($x, $y)
    {
        $keys    = array_keys ($x);
        $values  = array_values ($y);
    
        for ($x = 0; $x < count ($keys); $x++)
        {
            $newarray [$keys[$x]] = $y[$keys[$x]];
        }
        return $newarray;
    }
    
    print_r (match_arrayKeys ($gamey, $gamex)); 
    

    Output

    [wow] => World greatest
    [gw2] => best game
    [wiz101] => WTF?
    

提交回复
热议问题