PHP: Move associative array element to beginning of array

前端 未结 6 461
轮回少年
轮回少年 2020-12-12 17:02

What would be the best method of moving any element of an associative array to the beginning of the array?

For example, say I have the following array:



        
6条回答
  •  遥遥无期
    2020-12-12 17:35

    if you have 2 arrays, 1st has elements to move to the top of 2nd array of elements, you can use

    $result = \array_replace($ArrayToMoveToTop, $myArray);
    

    Here is a code sample:

    //source array    
    $myArray = [
        'two' => 'Blah Blah Blah 2',
        'three' => 'Blah Blah Blah 3',
        'one' => 'Blah Blah Blah 1',
        'four' => 'Blah Blah Blah 4',
        'five' => 'Blah Blah Blah 5',
    ];
    // set necessary order
    $orderArray = [
        'one' => '',
        'two' => '',
    ];
    //apply it
    $result = \array_replace($orderArray, $myArray);
    \print_r($result);
    

提交回复
热议问题