jackhao
jackhao

Reputation: 3857

How to insert array into associate array with a random order in PHP

I have an associate array with a bunch of arrays inside already.

I don't want to change the existing items' relative order(arrays already in the associative array), but, I'd like to insert new arrays into it with a random order(in between of the existing items). I tried multiple ways but none of them worked.

P.S.: I wrote a function which can insert array into associate array, but it always add array to the end of the associative array.

protected function array_push_assoc(&$array, $key, $value){
    $array[$key] = $value;
    return $array;
}

For example:

Original

array(
     'apple'=>50,
     'pear'=>10,
     'banana'=>20
);

After:

array(
     'apple'=>50,   //<=== This remains the same relative order to pear and banana
     'pear'=>10,    //<=== This remains the same relative order to apple and banana
     'something'=>15,    //<===== this is randomly put in here.
     'banana'=>20  //<=== This remains the same relative order to apple and pear
);

Upvotes: 0

Views: 79

Answers (1)

jackhao
jackhao

Reputation: 3857

OK in case anyone faces the same problem in the future, here is the solution:

            $random = rand(0, count($array) - 1);
            $array = array_slice($array, 0, $random, true) + array($key => $value) + array_slice($array, $random, count($array) - 1, true);

This will get the job done.

Upvotes: 1

Related Questions