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

后端 未结 5 1642
别跟我提以往
别跟我提以往 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:35

    Try this
    CODE

    $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple");
    ksort($fruits);
    foreach ($fruits as $key => $val) {
        echo "$key = $val\n";
    }
    

    OUTPUT

    a = orange
    b = banana
    c = apple
    d = lemon
    

    Check the php manual for ksort()

    0 讨论(0)
  • I can't think of any off the top of my head, but if the keys are the same across both arrays then why not just loop over the first one and use its key order to create a new array using the the values from the 2nd one?

    $arr1 = array(
        'a' => '42', 
        'b' => '551',
        'c' => '512',
        'd' => 'gge',
    ) ;
    
    
    $arr2 = array(
        'd' => 'ordered',
        'b' => 'is',
        'c' => 'now',
        'a' => 'this', 
    ) ;
    
    $arr2ordered = array() ;
    
    foreach (array_keys($arr1) as $key) {
        $arr2ordered[$key] = $arr2[$key] ;
    }
    
    0 讨论(0)
  • 2020-12-16 01:46
    foreach(array_keys($array1) as $key)
    {
      $tempArray[$key] = $array2[$key];
    }
    $array2 = $tempArray;
    
    0 讨论(0)
  • 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?
    
    0 讨论(0)
  • 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,
    
    ]
    
    0 讨论(0)
提交回复
热议问题