Use array_multisort() with custom function

后端 未结 2 2050
南旧
南旧 2021-01-26 18:46

I have the following array and I would like to sort it according another array and not DESC or ASC

$array = array(
    \'note\' => a         


        
2条回答
  •  半阙折子戏
    2021-01-26 19:19

    If you know the depth of the array you can simply apply usort on each array element to be sorted.

    Here is an example which orders according to a custom array:

     array_search($b, $order);
        });
    }
    unset($value);
    
    var_dump($array);
    /*
    array(2) {
      [0]=>
      array(4) {
        [0]=>
        string(5) "first"
        [1]=>
        string(6) "second"
        [2]=>
        string(5) "third"
        [3]=>
        string(6) "fourth"
      }
      [1]=>
      array(2) {
        [0]=>
        string(5) "first"
        [1]=>
        string(6) "second"
      }
    }
    */
    

    If you don't know how deep the array can go, the only solution that comes to my mind is a recursive function:

     array_search($b, $order);
                });
            }
        }
        return $array;
    }
    
    $array = custom_multisort($array, $order);
    
    var_dump($array);
    /*
    array(2) {
      [0]=>
      array(4) {
        [0]=>
        string(5) "first"
        [1]=>
        string(6) "second"
        [2]=>
        string(5) "third"
        [3]=>
        string(6) "fourth"
      }
      [1]=>
      array(2) {
        [0]=>
        array(2) {
          [0]=>
          string(5) "first"
          [1]=>
          string(6) "second"
        }
        [1]=>
        array(2) {
          [0]=>
          string(5) "third"
          [1]=>
          string(6) "fourth"
        }
      }
    }
    */
    

提交回复
热议问题