user2694306
user2694306

Reputation: 4050

Randomly Unset Element in Multidimensional Array if key-value Exists

I have a multidimensional array in PHP taking on the form of the following:

$data = array(
              array('spot'=>1,'name'=>'item_1'),
              array('spot'=>2,'name'=>'item_2'),
              array('spot'=>1,'name'=>'item_3'),
             );

If more than one array element contains a duplicate for the 'spot' number I would want to randomly select a single one and unset all other elements with the same 'spot' value. What would be the most efficient way to execute this? The resulting array would look like:

$data = array(
              array('spot'=>2,'name'=>'item_2'),
              array('spot'=>1,'name'=>'item_3'),
             );

Upvotes: 5

Views: 451

Answers (1)

Sharanya Dutta
Sharanya Dutta

Reputation: 4021

Store the values of spot in another array. Using array_count_values check which values occur more than once. Find the keys for those values. Select a random key. Delete all keys except the selected key from the original array. Here is the code:

$data = array(
              array('spot'=>1,'name'=>'item_1'),
              array('spot'=>2,'name'=>'item_2'),
              array('spot'=>1,'name'=>'item_3'),
        );


$arr = array();
foreach($data as $val){
    $arr[] = $val['spot'];
}

foreach(array_count_values($arr) as $x => $y){
    if($y == 1) continue;
    $keys = array_keys($arr, $x);
    $rand = $keys[array_rand($keys)];
    foreach($keys as $key){
        if($key == $rand) continue;
        unset($data[$key]);
    }
}

Upvotes: 3

Related Questions