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'),
);
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]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With