本文共 898 字,大约阅读时间需要 2 分钟。
要解决从多层嵌套数组中找到最大数并随机选择一个的问题,可以按照以下步骤进行:
max()函数找到数组中的最大值。mt_rand()函数随机选择一个;否则,直接选择最大值。以下是实现代码:
function get_all_numbers($array) { $result = array(); foreach ($array as $key => $value) { if (is_array($value)) { $result = array_merge($result, get_all_numbers($value)); } else { $result[] = $value; } } return $result;}$numbers = get_all_numbers($array);$max = max($numbers);$max_count = count(array_filter($numbers, function($val) { return $val == $max; }));if ($max_count > 1) { $max_value = $numbers[array_search($max, $numbers) + mt_rand(0, count($numbers) - array_search($max, $numbers))];} else { $max_value = $max;} 这个代码首先使用get_all_numbers函数递归遍历整个数组,收集所有数字到$numbers数组中。然后,使用max()函数找到最大值,并统计最大值的出现次数。如果最大值出现多次,使用mt_rand()函数随机选择一个;否则,直接选择最大值作为结果。
转载地址:http://xttfk.baihongyu.com/