Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly Unset Element in Multidimensional Array if key-value Exists

Tags:

arrays

php

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'),
             );
like image 958
user2694306 Avatar asked Oct 20 '22 00:10

user2694306


1 Answers

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]);
    }
}
like image 141
Sharanya Dutta Avatar answered Nov 03 '22 09:11

Sharanya Dutta