Randomly unlock an item in a multidimensional array if a key value exists

I have a multidimensional array in PHP that takes the following form:

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

If more than one element of the array contains a duplicate for the number "spot", I would like to randomly select one and delete all other elements with the same value "spot". What would be the most efficient way to accomplish this? The resulting array will look like this:

$data = array(
              array('spot'=>2,'name'=>'item_2'),
              array('spot'=>1,'name'=>'item_3'),
             );
+4
source share
1 answer

spot . array_count_values, , . . . , . :

$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]);
    }
}
+2

All Articles